Java 8
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");
}
}
Output:
--- 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);
where compareThem
has to be added in MyType.java:
public static int compareThem(MyType a, MyType b) {
return a.name.compareTo(b.name);
}
Comparator
and use it for sorting. – ThalamusComparator
split the string and use the first element as the name. – Baillieu