Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a conditional sorting in Java 8

Let us say I have a list of points returned with a sort function:

List<Point> points = new ArrayList<>(); 
points.add(new Point(3, 30)); 
points.add(new Point(1, 10)); 
points.add(new Point(2, 20));

points.stream() 
.sorted((p1, p2)->p1.x.compareTo(p2.x)) 
.forEach(System.out::println);

How do I make sorted(...) conditional based on a boolean flag (sortThePoints), something like the below

points.stream()
if(sortThePoints){
 .sorted((p1, p2)->p1.x.compareTo(p2.x)) 
}
.forEach(System.out::println);
like image 536
FakirTrappedInCode Avatar asked Dec 14 '22 09:12

FakirTrappedInCode


1 Answers

Stream.sorted(Comparator) makes a stable sort if the stream is ordered. In other words, if two elements are equals then they'll keep their initial ordering.

static final Comparator<Point> identityComparator = (p1, p2) -> 0;

Comparator<Point> normalComparator = (p1, p2)->p1.x.compareTo(p2.x);

(or Comparator<Point> normalComparator = Comparator.comparing(p -> p.x))

points.stream()
.sorted(sortThePoints ? normalComparator : identityComparator)
.forEach(System.out::println);
like image 156
Mạnh Quyết Nguyễn Avatar answered Jan 31 '23 04:01

Mạnh Quyết Nguyễn