I have a Distance object which have a totalDistance attribute. Using java 8 steams I need to sort a List by the totalDistance.
I know that I could sort this list by using something like:
.sorted(Comparator.comparing(Distance::totalDistance).reversed())
My problem though is that I need to sort it by a specific range.
For example, sort the distance getting the first 50, then getting from 50 to 100, and so on... but through those intervals it should not be ordered.
For example, with the following list:
List<Distance> list = new ArrayList<>();
list.add(new Distance(100));
list.add(new Distance(10));
list.add(new Distance(1));
list.add(new Distance(40));
list.add(new Distance(30));
Sorting by range I would get:
10,1,40,30,100
Any Idea of how to implement this kind of sorted range interval using java 8?
I'm fairly certain that you can divide the value by your range's length (50, in this case) when comparing them:
List<Distance> list = Arrays.asList(new Distance(130),
new Distance(100), new Distance(10),
new Distance(1), new Distance(40), new Distance(30), new Distance(120)
);
list.sort(Comparator.comparingInt(d -> d.getTotalDistance() / 50));
list.stream().mapToInt(Distance::getTotalDistance).forEach(System.out::println); // assuming the getter for 'totalDistance'
Output:
1 40 30 130 100 120
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