My array does not contain any string. But its contains object references. Every object reference returns name, id, author and publisher by toString method.
public String toString() { return (name + "\n" + id + "\n" + author + "\n" + publisher + "\n"); }
Now I need to sort that array of objects by the name. I know how to sort, but I do not know how to extract the name from the objects and sort them.
To sort an array of objects using the Arrays. sort method in Java, we can have the class implement the Comparable interface, which then imposes a natural ordering on its objects.
To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.
Implement a Comparator and pass your array along with the comparator to the sort method which take it as second parameter. Implement the Comparable interface in the class your objects are from and pass your array to the sort method which takes only one parameter.
To sort an Object by its property, you have to make the Object implement the Comparable interface and override the compareTo() method. Lets see the new Fruit class again. The new Fruit class implemented the Comparable interface, and overrided the compareTo() method to compare its quantity property in ascending order.
You can try something like this:
List<Book> books = new ArrayList<Book>(); Collections.sort(books, new Comparator<Book>(){ public int compare(Book o1, Book o2) { return o1.name.compareTo(o2.name); } });
You have two ways to do that, both use the Arrays utility class
Example
class Book implements Comparable<Book> { public String name, id, author, publisher; public Book(String name, String id, String author, String publisher) { this.name = name; this.id = id; this.author = author; this.publisher = publisher; } public String toString() { return ("(" + name + ", " + id + ", " + author + ", " + publisher + ")"); } @Override public int compareTo(Book o) { // usually toString should not be used, // instead one of the attributes or more in a comparator chain return toString().compareTo(o.toString()); } } @Test public void sortBooks() { Book[] books = { new Book("foo", "1", "author1", "pub1"), new Book("bar", "2", "author2", "pub2") }; // 1. sort using Comparable Arrays.sort(books); System.out.println(Arrays.asList(books)); // 2. sort using comparator: sort by id Arrays.sort(books, new Comparator<Book>() { @Override public int compare(Book o1, Book o2) { return o1.id.compareTo(o2.id); } }); System.out.println(Arrays.asList(books)); }
Output
[(bar, 2, author2, pub2), (foo, 1, author1, pub1)] [(foo, 1, author1, pub1), (bar, 2, author2, pub2)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With