宝慕林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);}