You can create a Comparator object to sort Collections, arrays, etc.
Comparators can be created in two ways:
- Anonymous class
- Lambda Expressions
Create Comparator with anonymous class
You can create a Comparator with an anonymous class. The return value of compare()
can be negative, positive, or zero.
If a negative number is returned, the right argument is moved down.
public void comparatorExample1() {
List<String> strings = new ArrayList<>();
strings.add("This code is free software");
strings.add("you can redistribute it");
strings.add("under the terms of the GNU General Public License version 2 only");
strings.add("This code is distributed in the hope that it will be useful");
strings.add("Please contact Oracle");
strings.add("500 Oracle Parkway, Redwood Shores, CA 94065 USA");
// before sorting
for (String str : strings) {
System.out.println(str);
}
// sorting by character length (ascending order)
Collections.sort(strings, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
});
// out after sorting
System.out.println();
for (String str : strings) {
System.out.println(str);
}
}
result
This code is free software
you can redistribute it
under the terms of the GNU General Public License version 2 only
This code is distributed in the hope that it will be useful
Please contact Oracle
500 Oracle Parkway, Redwood Shores, CA 94065 USA
Please contact Oracle
you can redistribute it
This code is free software
500 Oracle Parkway, Redwood Shores, CA 94065 USA
This code is distributed in the hope that it will be useful
under the terms of the GNU General Public License version 2 only
Create Comparator with Lambda Expression
Anonymous classes can also be expressed as lambda expressions.
public void comparatorExample2() {
List<String> strings = new ArrayList<>();
strings.add("This code is free software");
strings.add("you can redistribute it");
strings.add("under the terms of the GNU General Public License version 2 only");
strings.add("This code is distributed in the hope that it will be useful");
strings.add("Please contact Oracle");
strings.add("500 Oracle Parkway, Redwood Shores, CA 94065 USA");
// before sorting
for (String str : strings) {
System.out.println(str);
}
// sorting by character length (ascending order)
Collections.sort(strings, (s1, s2) -> s1.length() - s2.length());
// out after sorting
System.out.println();
for (String str : strings) {
System.out.println(str);
}
}
result
This code is free software
you can redistribute it
under the terms of the GNU General Public License version 2 only
This code is distributed in the hope that it will be useful
Please contact Oracle
500 Oracle Parkway, Redwood Shores, CA 94065 USA
Please contact Oracle
you can redistribute it
This code is free software
500 Oracle Parkway, Redwood Shores, CA 94065 USA
This code is distributed in the hope that it will be useful
under the terms of the GNU General Public License version 2 only
Differences from Comparables
Comparable is an interface, and if a class implements this interface, it can be used to sort a list, etc.
public interface Comparable<T> {
public int compareTo(T o);
}
Comparable ascompareTo()
method and implement the code that compares two objects (this and its argument).
public class Text implements Comparable<Text> {
private String mText;
public Text(String text) {
mText = text;
}
public String getText() {
return mText;
}
@Override
public int compareTo(@NotNull Text right) {
return getText().length() - right.getText().length();
}
}
And you can sort by calling Collections.sort()
like this:
public void comparableExample1() {
List<Text> texts = new ArrayList<>();
texts.add(new Text("This code is free software"));
texts.add(new Text("you can redistribute it"));
texts.add(new Text("under the terms of the GNU General Public License version 2 only"));
texts.add(new Text("This code is distributed in the hope that it will be useful"));
texts.add(new Text("Please contact Oracle"));
texts.add(new Text("500 Oracle Parkway, Redwood Shores, CA 94065 USA"));
// before sorting
for (Text text : texts) {
System.out.println(text.getText());
}
// sorting by character length (ascending order)
Collections.sort(texts);
// out after sorting
System.out.println();
for (Text text : texts) {
System.out.println(text.getText());
}
}
For more details, refer to Java - How to Sort with Comparator.
Related Posts
- Java - Remove items from List while iterating
- Java - How to find key by value in HashMap
- Java - Update the value of a key in HashMap
- Java - How to put quotes in a string
- Java - How to put a comma (,) after every 3 digits
- BiConsumer example in Java 8
- Java 8 - Consumer example
- Java 8 - BinaryOperator example
- Java 8 - BiPredicate Example
- Java 8 - Predicate example
- Java 8 - Convert Stream to List
- Java 8 - BiFunction example
- Java 8 - Function example
- Java - Convert List to Map
- Exception testing in JUnit
- Hamcrest Collections Matcher
- Hamcrest equalTo () Matcher
- AAA pattern of unit test (Arrange/Act/Assert)
- Hamcrest Text Matcher
- Hamcrest Custom Matcher
- Why Junit uses Hamcrest
- Java - ForkJoinPool
- Java - How to use Futures
- Java - Simple HashTable implementation
- Java - Create a file in a specific path
- Java - Mockito의 @Mock, @Spy, @Captor, @InjectMocks
- Java - How to write test code using Mockito
- Java - Synchronized block
- Java - How to decompile a ".class" file into a Java file (jd-cli decompiler)
- Java - How to generate a random number
- Java - Calculate powers, Math.pow()
- Java - Calculate the square root, Math.sqrt()
- Java - How to compare String (==, equals, compare)
- Java - Calculate String Length
- Java - case conversion & comparison insensitive (toUpperCase, toLowerCase, equalsIgnoreCase)