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.
Java 8
Using lambda expressions
Test.java
MyType.java
Output:
Using method references
where
compareThem
has to be added in MyType.java:You can try something like this:
You can implement the "Comparable" interface on a class whose objects you want to compare.
And also implement the "compareTo" method in that.
Add the instances of the class in an ArrayList
Then the "java.utils.Collections.sort()" method will do the necessary magic.
Here's--->(https://deva-codes.herokuapp.com/CompareOnTwoKeys) a working example where objects are sorted based on two keys first by the id and then by name.
You have two ways to do that, both use the Arrays utility class
Example
Output