This is what you want (Java 8)
import java.util.Comparator;
public class ComparatorDemo {
public static void main(String... args) {
// (1) Defining a custom comparator using lambda
// Comparator<Integer> c = (Integer a, Integer b) -> a - b;
// (2) comparingInt takes a lambda which maps from object you want to compare to an int
Comparator<Integer> c = Comparator.comparingInt(a -> a);
if (c.compare(3, 5) < 0)
System.out.println("Yes, It's less");
}
}
Using a comparator however, would make more sense in case of slightly more complex classes. For example, here is what you would do if you wanted a comparator to compare two points using their x-coordinate
import java.util.Comparator;
class Point {
private int x;
private int y;
public Point(int x, int y) { this.x = x; this.y = y; }
public int getY() { return y; }
public void setY(int y) { this.y = y; }
public int getX() { return x; }
public void setX(int x) { this.x = x; }
}
public class ComparatorDemo {
public static void main(String... args) {
Comparator<Point> pc = Comparator.comparing(Point::getX);
Point p1 = new Point(1, 2);
Point p2 = new Point(2, 2);
if (pc.compare(p1, p2) < 0) {
System.out.println("Yes, it's less");
}
}
}