EN
Java TreeMap Comparable vs Comparator, can someone share practical example how to use it?
1
answers
2
points
Java TreeMap Comparable vs Comparator, can someone share practical example how to use it?
1 answer
5
points
Here is practical example with TreeMap and Comparable vs Comparator:
import org.junit.Test;
import java.util.Comparator;
import java.util.TreeMap;
import static org.assertj.core.api.Assertions.assertThat;
public class ComparableVsComparatorExample {
@Test
public void test() {
{
// Point1 implements Comparable<Point1>
TreeMap<Point1, String> map1 = new TreeMap<>();
map1.put(new Point1(1, 2), "pt1");
map1.put(new Point1(1, 2), "pt1-override"); // override value for key: Point(1, 2)
map1.put(new Point1(2, 1), "pt2");
assertThat(map1).hasSize(2);
assertThat(map1.get(new Point1(1, 2))).isEqualTo("pt1-override");
assertThat(map1.get(new Point1(2, 1))).isEqualTo("pt2");
assertThat(map1.toString())
.isEqualTo("{Point{x=1, y=2}=pt1-override, Point{x=2, y=1}=pt2}");
}
{
// Point2 doesn't implement Comparable,
// but we pass Comparator<Point2> implementation via TreeMap constructor
TreeMap<Point2, String> map2 = new TreeMap<>(new Comparator<Point2>() {
@Override
public int compare(Point2 o1, Point2 o2) {
// asc order
int compareX = Integer.compare(o1.getX(), o2.getX());
if (compareX == 0) { // eq
return Integer.compare(o1.getY(), o2.getY());
}
return compareX; // -1 or 1 - if o1X < o2X ret -1, if o1X > o2X ret 1
}
});
map2.put(new Point2(1, 2), "pt1");
map2.put(new Point2(1, 2), "pt1-override"); // override value for key: Point(1, 2)
map2.put(new Point2(2, 1), "pt2");
assertThat(map2).hasSize(2);
assertThat(map2.get(new Point2(1, 2))).isEqualTo("pt1-override");
assertThat(map2.get(new Point2(2, 1))).isEqualTo("pt2");
assertThat(map2.toString())
.isEqualTo("{Point{x=1, y=2}=pt1-override, Point{x=2, y=1}=pt2}");
}
}
private static class Point1 implements Comparable<Point1> {
private final int x;
private final int y;
public Point1(int x, int y) {this.x = x;this.y = y;}
public int getX() {return x;}
public int getY() {return y;}
@Override
public String toString() {return "Point{" + "x=" + x + ", y=" + y + '}';}
@Override
public int compareTo(Point1 o2) {
// asc order
Point1 o1 = this;
int compareX = Integer.compare(o1.getX(), o2.getX());
if (compareX == 0) { // eq
return Integer.compare(o1.getY(), o2.getY());
}
return compareX; // -1 or 1 - if o1X < o2X ret -1, if o1X > o2X ret 1
}
}
private static class Point2 {
private final int x;
private final int y;
public Point2(int x, int y) {this.x = x;this.y = y;}
public int getX() {return x;}
public int getY() {return y;}
@Override
public String toString() {return "Point{" + "x=" + x + ", y=" + y + '}';}
}
}
0 comments
Add comment