-
Comparable, Comparator, and Collection SortStaticPL/JAVA 2020. 3. 15. 19:24
1. Overview
Comparable Comparator Comparable interface is used to sort the objects with natural ordering. Comparator in Java is used to sort the attributes of different objects. Comparable interface compares “this” reference with the object specified. Comparator in Java compares two different class objects provided. Comparable is present in java.lang package. A Comparator is present in the java.util package. Comparable affects the original class, i.e., the actual class is modified. Comparator doesn’t affect the original class Comparable provides compareTo() method to sort elements. Comparator provides compare() method, equals() method to sort elements. 2. compareTo() method
The compareTo() method compares a given object or the current instance with a specified object to determine the order of objects. Here’s a quick look at how compareTo() works:
If the comparison returns
Then ...
>= 1
this.name > simpson.name
0
this.name == simpson.name
<= -1
this.name < simpson.name
We can only use classes that are comparable with the sort() method. If we try to pass a Simpson that does not implement Comparable, we will receive a compilation error.
The sort() method uses polymorphism bypassing any object that is Comparable. Objects will then be sorted as expected.
2. Example
class ComparableTest implements Comparable<ComparableTest> { private int age; public ComparableTest(int age){ this.age = age; } @Override public int compareTo(ComparableTest o) { return this.age - o.age; } @Override public String toString() { return String.valueOf(this.age); } } class ComparatorTest implements Comparator<Integer> { @Override public int compare(Integer o1, Integer o2) { return o1 - o2; } } //@FunctionalInterface //interface comparatorFt extends Comparator<Integer> { // void apply(); //} public class Main { public static void main(String[] args) { ComparableTest c1 = new ComparableTest(4); ComparableTest c2 = new ComparableTest(5); ComparableTest c3 = new ComparableTest(1); ComparableTest c4 = new ComparableTest(8); ComparableTest c5 = new ComparableTest(6); // ComparatorTest ct1 = new ComparatorTest(4); // ComparatorTest ct2 = new ComparatorTest(5); // ComparatorTest ct3 = new ComparatorTest(1); // ComparatorTest ct4 = new ComparatorTest(8); // ComparatorTest ct5 = new ComparatorTest(6); ComparableTest[] cs = new ComparableTest[] {c1, c2, c3, c4, c5}; Arrays.sort(cs); // for (ComparableTest c: cs) { // System.out.println(c); // } Integer arr[] = new Integer[] {5,2,6,5,2,54,72,16,5,472,5,62,45,3}; Arrays.sort(arr, new ComparatorTest()); for (Integer c: arr) { System.out.println(c); } Integer a = 3; } }
3. Collection.sort()
Using the Comparable interface and compareTo() method, we can sort using alphabetical order, String length, reverse alphabetical order, or numbers. The Comparator interface allows us to do the same but in a more flexible way.
3.1 Comparable Example
Note that we’ve overridden the compareTo() method and passed in another Simpson object.
class Simpson implements Comparable<Simpson> { String name; Simpson(String name) { this.name = name; } @Override public int compareTo(Simpson simpson) { return this.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 -> s.name).forEach(System.out::print); Collections.reverse(simpsons); simpsons.stream().forEach(System.out::print); } }
3.2 Comparator Example
Use Comparable when there is a single, default comparison for your object. Use Comparatorwhen you need to work around 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.
public class BadExampleOfComparable { public static void main(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) { return this.name.length() - (simpson.name.length()); } }; characters.add(homer); characters.add(moe); Collections.sort(characters); System.out.println(characters); } }
public class GoodExampleOfComparator { public static void main(String... args) { List<SimpsonCharacter> characters = new ArrayList<>(); SimpsonCharacter homer = new SimpsonCharacter("Homer"); SimpsonCharacter moe = new SimpsonCharacter("Moe"); characters.add(homer); characters.add(moe); Collections.sort(characters, (Comparator.<SimpsonCharacter> comparingInt(character1 -> character1.name.length()) .thenComparingInt(character2 -> character2.name.length()))); System.out.println(characters); } }
public class MarvelComparator { public static void main(String... comparator) { List<String> marvelHeroes = new ArrayList<>(); marvelHeroes.add("SpiderMan "); marvelHeroes.add("Wolverine "); marvelHeroes.add("Xavier "); marvelHeroes.add("Cyclops "); Collections.sort(marvelHeroes, new Comparator<String>() { @Override public int compare(String 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); } }
4. Reference
https://www.edureka.co/blog/comparable-in-java/
https://wjheo.tistory.com/entry/Java-%EC%A0%95%EB%A0%AC%EB%B0%A9%EB%B2%95-Collectionssort
'StaticPL > JAVA' 카테고리의 다른 글
Optional (0) 2020.06.24 Non-blocking, Lock-free operations (0) 2020.02.27 Semaphore (0) 2020.02.27 ReentrantReadWriteLock (0) 2020.02.27 ReentrantLock, lockInterruptibly, and tryLock (0) 2020.02.27