如何在Java中对对象数组进行排序?

如何在Java中对对象数组进行排序?

我的数组不包含任何字符串。但它包含对象引用。每个对象引用都通过toString方法返回name,id,author和publisher。

public String toString() {
        return (name + "\n" + id + "\n" + author + "\n" + publisher + "\n");}

现在我需要按名称对对象数组进行排序。我知道如何排序,但我不知道如何从对象中提取名称并对它们进行排序。


慕桂英546537
浏览 1941回答 3
3回答

宝慕林4294392

Java 8使用lambda表达式Arrays.sort(myTypes, (a,b) -> a.name.compareTo(b.name));Test.javapublic class Test {     public static void main(String[] args) {         MyType[] myTypes = {                 new MyType("John", 2, "author1", "publisher1"),                 new MyType("Marry", 298, "author2", "publisher2"),                 new MyType("David", 3, "author3", "publisher3"),         };         System.out.println("--- before");         System.out.println(Arrays.asList(myTypes));         Arrays.sort(myTypes, (a, b) -> a.name.compareTo(b.name));         System.out.println("--- after");         System.out.println(Arrays.asList(myTypes));     }}MyType.javapublic class MyType {     public String name;     public int id;     public String author;     public String publisher;     public MyType(String name, int id, String author, String publisher) {         this.name = name;         this.id = id;         this.author = author;         this.publisher = publisher;     }     @Override     public String toString() {         return "MyType{" +                 "name=" + name + '\'' +                 ", id=" + id +                 ", author='" + author + '\'' +                 ", publisher='" + publisher + '\'' +                 '}' + System.getProperty("line.separator");     }}输出:--- before[MyType{name=John', id=2, author='author1', publisher='publisher1'}, MyType{name=Marry', id=298, author='author2', publisher='publisher2'}, MyType{name=David', id=3, author='author3', publisher='publisher3'}]--- after[MyType{name=David', id=3, author='author3', publisher='publisher3'}, MyType{name=John', id=2, author='author1', publisher='publisher1'}, MyType{name=Marry', id=298, author='author2', publisher='publisher2'}]使用方法引用Arrays.sort(myTypes, MyType::compareThem);其中,compareThem已经在加入MyType.java:public static int compareThem(MyType a, MyType b) {     return a.name.compareTo(b.name);}
打开App,查看更多内容
随时随地看视频慕课网APP