如何在Java中对对象数组进行排序?我的数组不包含任何字符串。但它包含对象引用。每个对象引用都通过toString方法返回name,id,author和publisher。public String toString() {
return (name + "\n" + id + "\n" + author + "\n" + publisher + "\n");}现在我需要按名称对对象数组进行排序。我知道如何排序,但我不知道如何从对象中提取名称并对它们进行排序。
3 回答
宝慕林4294392
TA贡献2021条经验 获得超8个赞
Java 8
使用lambda表达式
Arrays.sort(myTypes, (a,b) -> a.name.compareTo(b.name));
Test.java
public 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.java
public 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);}
添加回答
举报
0/150
提交
取消