Reputation: 21
I would like to sort a List<List<LocalTime>>
with stream()
.
This is what the List
looks like:
[[21:29, 22:29], [16:29, 17:29]]
and I would like the list to be like this
[[16:29, 17:29], [21:29, 22:29]]
Upvotes: 1
Views: 408
Reputation: 79085
You can define a comparator as described in this answer and perform the sorting.
Demo:
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.IntStream;
public class Main {
public static void main(String args[]) {
List<List<LocalTime>> list =
new ArrayList<>(List.of(
new ArrayList<>(List.of(LocalTime.of(21, 29), (LocalTime.of(22, 29)))),
new ArrayList<>(List.of(LocalTime.of(16, 29), (LocalTime.of(17, 29))))
));
Comparator<List<LocalTime>> comparator =
(list1, list2) ->
IntStream.range(0, list1.size())
.map(i -> list1.get(i).compareTo(list2.get(i)))
.filter(value -> value != 0)
.findFirst()
.orElse(0);
list.sort(comparator);
System.out.println(list);
}
}
Output:
[[16:29, 17:29], [21:29, 22:29]]
Upvotes: 1