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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With