Java How To Sort Set
Sorting with Comparable and Comparator in Java
Comparable or Comparator—which should it be? Acquire how to choose the correct interface for the sorting algorithm you demand.
- Sorting a Java List with a custom object
- The compareTo() method
- Sorting a Java array
- Can I sort objects without Comparable?
- Sorting with Comparator
- Are the core Java classes Comparable?
- Take the Comparable interface challenge!
- Larn more about Coffee
Evidence More
Programmers oftentimes need to sort elements from a database into a collection, array, or map. In Java, we tin implement any sorting algorithm nosotros desire with whatever type. Using the Comparable interface and compareTo() method, we tin sort using alphabetical society, Cord length, reverse alphabetical order, or numbers. The Comparator interface allows us to practise the same but in a more flexible manner.
Any nosotros want to exercise, we only need to know how to implement the right sort logic for the given interface and type.
Sorting a Java List with a custom object
For our example nosotros'll use the aforementioned POJO we've used for other Java Challengers then far. In this first case, nosotros implement the Comparable interface in the Simpson grade, using Simpson in the generic type:
class Simpson implements Comparable<Simpson> { String name; Simpson(String proper name) { this.name = name; } @Override public int compareTo(Simpson simpson) { return this.proper name.compareTo(simpson.name); } } public class SimpsonSorting { public static void main(String... sortingWithList) { List<SimpsonCharacter> simpsons = new ArrayList<>(); simpsons.add(new SimpsonCharacter("Homer ")); simpsons.add(new SimpsonCharacter("Marge ")); simpsons.add(new SimpsonCharacter("Bart ")); simpsons.add(new SimpsonCharacter("Lisa ")); Collections.sort(simpsons); simpsons.stream().map(s -> southward.proper name).forEach(System.out::print); Collections.reverse(simpsons); simpsons.stream().forEach(System.out::print); } } Note that we've overridden the compareTo() method and passed in another Simpson object. We've also overridden the toString() method, just to make the instance easier to read.
The compareTo() method
The compareTo() method compares a given object or the electric current example with a specified object to determine the guild of objects. Here's a quick look at how compareTo() works:
| If the comparison returns | And then ... |
| | |
| | |
| | |
We can only use classes that are comparable with the sort() method. If we attempt to pass a Simpson that does not implement Comparable, we will receive a compilation error.
The sort() method uses polymorphism by passing whatsoever object that is Comparable. Objects will then be sorted equally expected.
The output from the previous lawmaking would be:
Bart Homer Lisa Marge If we wanted to reverse the order, nosotros could exchange the sort() for a contrary(); from:
Collections.sort(simpsons); to:
Collections.reverse(simpsons); Deploying the reverse() method would change the previous output to:
Marge Lisa Homer Bart Sorting a Coffee assortment
In Java, nosotros can sort an array with any blazon nosotros want equally long as it implements the Comparable interface. Here's an example:
public class ArraySorting { public static void principal(String... moeTavern) { int[] moesPints = new int[] {9, eight, 7, 6, ane}; Arrays.sort(moesPints); Arrays.stream(moesPints).forEach(Organization.out::print); Simpson[] simpsons = new Simpson[]{new Simpson("Lisa"), new Simpson("Homer")}; Arrays.sort(simpsons); Arrays.stream(simpsons).forEach(System.out::println); } } In the first sort() invocation, the array is sorted to:
1 6 7 8 9 In the second sort() invocation, it is sorted to:
Homer Lisa Keep in mind that custom objects must implement Comparable in gild to be sorted, even as an assortment.
Can I sort objects without Comparable?
If the Simpson object wasn't implementing Comparable, a ClassCastException would be thrown. If you lot run this equally a examination, you will see something like the post-obit output:
Mistake:(xvi, 20) java: no suitable method found for sort(java.util.List<com.javaworld.javachallengers.sortingcomparable.Simpson>) method java.util.Collections.<T>sort(java.util.List<T>) is non applicable (inference variable T has incompatible bounds equality constraints: com.javaworld.javachallengers.sortingcomparable.Simpson lower bounds: coffee.lang.Comparable<? super T>) method java.util.Collections.<T>sort(java.util.Listing<T>,java.util.Comparator<? super T>) is not applicable (cannot infer type-variable(s) T (actual and formal argument lists differ in length)) This log may be disruptive, but don't worry. Just keep in heed that a ClassCastException will be thrown for any sorted object that doesn't implement the Comparable interface.
Sorting a Map with TreeMap
The Java API includes many classes to help with sorting, including TreeMap. In the example beneath, we use TreeMap to sort keys into a Map.
public class TreeMapExample { public static void principal(Cord... barney) { Map<SimpsonCharacter, String> simpsonsCharacters = new TreeMap<>(); simpsonsCharacters.put(new SimpsonCharacter("Moe"), "shotgun"); simpsonsCharacters.put(new SimpsonCharacter("Lenny"), "Carl"); simpsonsCharacters.put(new SimpsonCharacter("Homer"), "television"); simpsonsCharacters.put(new SimpsonCharacter("Barney"), "beer"); System.out.println(simpsonsCharacters); } } TreeMap uses the compareTo() method implemented past the Comparable interface. Each element in the resulting Map is sorted past its fundamental. In this case, the output would be:
Barney=beer, Homer=tv, Lenny=Carl, Moe=shotgun Remember, though: if the object doesn't implement Comparable, a ClassCastException volition be thrown.
Sorting a Set with TreeSet
The Set interface is responsible for storing unique values, simply when nosotros apply the TreeSet implementation, inserted elements will be automatically sorted equally we add them:
public grade TreeSetExample { public static void primary(String... barney) { Set<SimpsonCharacter> simpsonsCharacters = new TreeSet<>(); simpsonsCharacters.add together(new SimpsonCharacter("Moe")); simpsonsCharacters.add(new SimpsonCharacter("Lenny")); simpsonsCharacters.add(new SimpsonCharacter("Homer")); simpsonsCharacters.add(new SimpsonCharacter("Barney")); System.out.println(simpsonsCharacters); } } The output from this lawmaking is:
Barney, Homer, Lenny, Moe Once more, if we utilise an object that is not Comparable, a ClassCastException volition be thrown.
Sorting with Comparator
What if we didn't want to use the same compareTo() method from the POJO class? Could we override the Comparable method to employ a dissimilar logic? Below is an example:
public class BadExampleOfComparable { public static void master(String... args) { List<SimpsonCharacter> characters = new ArrayList<>(); SimpsonCharacter homer = new SimpsonCharacter("Homer") { @Override public int compareTo(SimpsonCharacter simpson) { return this.name.length() - (simpson.name.length()); } }; SimpsonCharacter moe = new SimpsonCharacter("Moe") { @Override public int compareTo(SimpsonCharacter simpson) { render this.name.length() - (simpson.name.length()); } }; characters.add together(homer); characters.add together(moe); Collections.sort(characters); System.out.println(characters); } } As you can run into, this code is complicated and includes a lot of repetition. We had to override the compareTo() method twice for the same logic. If there were more than elements we would take to replicate the logic for each object.
Fortunately, we have the Comparator interface, which lets united states disassemble the compareTo() logic from Java classes. Consider the same example above rewritten using Comparator:
public class GoodExampleOfComparator { public static void chief(String... args) { List<SimpsonCharacter> characters = new ArrayList<>(); SimpsonCharacter homer = new SimpsonCharacter("Homer"); SimpsonCharacter moe = new SimpsonCharacter("Moe"); characters.add together(homer); characters.add together(moe); Collections.sort(characters, (Comparator.<SimpsonCharacter> comparingInt(character1 -> character1.name.length()) .thenComparingInt(character2 -> character2.name.length()))); System.out.println(characters); } } These examples demonstrate the main difference between Comparable and Comparator.
Use Comparable when there is a single, default comparison for your object. Utilise Comparatorwhen yous demand to work effectually an existing compareTo(), or when you need to use specific logic in a more flexible way. Comparator detaches the sorting logic from your object and contains the compareTo() logic within your sort() method.
Using Comparator with an anonymous inner class
In this next example, we apply an anonymous inner course to compare the value of objects. An anonymous inner class, in this case, is any grade that implements Comparator. Using information technology ways we are not bound to instantiating a named class implementing an interface; instead, we implement the compareTo() method inside the anonymous inner class.
public form MarvelComparator { public static void main(String... comparator) { Listing<String> marvelHeroes = new ArrayList<>(); marvelHeroes.add together("SpiderMan "); marvelHeroes.add("Wolverine "); marvelHeroes.add("Xavier "); marvelHeroes.add("Cyclops "); Collections.sort(marvelHeroes, new Comparator<Cord>() { @Override public int compare(Cord hero1, String hero2) { return hero1.compareTo(hero2); } }); Collections.sort(marvelHeroes, (m1, m2) -> m1.compareTo(m2)); Collections.sort(marvelHeroes, Comparator.naturalOrder()); marvelHeroes.forEach(System.out::print); } } Using Comparator with lambda expressions
Anonymous inner classes are verbose, which can cause issues in our code. In the Comparator interface, we can use lambda expressions to simplify and make the code easier to read. For case, we could modify this:
Collections.sort(marvel, new Comparator<String>() { @Override public int compare(String hero1, String hero2) { return hero1.compareTo(hero2); } }); to this:
Collections.sort(marvel, (m1, m2) -> m1.compareTo(m2)); Less code and the aforementioned result!
The output of this code would exist:
Cyclops SpiderMan Wolverine Xavier We could brand the lawmaking even simpler past irresolute this:
Collections.sort(marvel, (m1, m2) -> m1.compareTo(m2)); to this:
Collections.sort(marvel, Comparator.naturalOrder()); Are the core Java classes Comparable?
Many cadre Java classes and objects implement the Comparable interface, which ways nosotros don't have to implement the compareTo() logic for those classes. Here are a few familiar examples:
Cord
public final form String implements coffee.io.Serializable, Comparable<String>, CharSequence { ... Integer
public terminal class Integer extends Number implements Comparable<Integer> { … Double
public final class Double extends Number implements Comparable<Double> {... In that location are many others. I encourage you to explore the Java cadre classes to learn their of import patterns and concepts.
Take the Comparable interface challenge!
Test what you lot've learned by figuring out the output of the following code. Remember, you'll learn best if you solve this claiming for yourself just by studying it. Once y'all've reached an answer, y'all tin can bank check the answer below. You tin also run your own tests to fully absorb the concepts.
public class SortComparableChallenge { public static void main(String... doYourBest) { Set<Simpson> set up = new TreeSet<>(); set.add(new Simpson("Homer")); set.add together(new Simpson("Marge")); set.add(new Simpson("Lisa")); set.add(new Simpson("Bart")); set.add(new Simpson("Maggie")); Listing<Simpson> list = new ArrayList<>(); list.addAll(ready); Collections.reverse(list); listing.forEach(System.out::println); } static class Simpson implements Comparable<Simpson> { Cord proper noun; public Simpson(String name) { this.name = name; } public int compareTo(Simpson simpson) { return simpson.name.compareTo(this.proper noun); } public String toString() { return this.name; } } } Source: https://www.infoworld.com/article/3323403/java-challengers-5-sorting-with-comparable-and-comparator-in-java.html

0 Response to "Java How To Sort Set"
Post a Comment