Comparable is an interface, and if a class implements this interface, it can be used to sort a list, etc.
The return value of Comparables
compareTo()` method can be negative, positive, or zero.
If a negative number is returned, the order of the arguments is moved down.
public interface Comparable<T> {
public int compareTo(T o);
}
Class that implements Comparable
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();
}
}
sorting
If you pass a list of Comparable objects as an argument to Collections.sort()
, sorting is performed. The criteria for sorting is the compareTo() method implemented above.
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());
}
}
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 Comparator
Comparator is a class that has rules for sorting.
The return value of compare()
can be negative, positive, or zero.
Since it is usually used only once and not used, it is made as an anonymous object as follows.
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");
Collections.sort(strings, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
});
result
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
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)