问题描述:

Thanks to eran, I have the following Lambda which creates a list of list of myType. MyType contains a field named dateOfContainer.

My question now would be if there is a possibility to extends the expression in order to sort the List<MyType> of List<List<MyType>> list by dateOfContainer?

List<List<MyType>> list = new ArrayList<> (

myList.stream().collect (Collectors.groupingBy(MyType::getDateOfContainer)).values());

[EDIT]

Thanks a lot for the suggestions. Iam still fighting witch this expression. My current expression looks like this:

List<List<ScheduleIntervalContainer>> list = new ArrayList<>(

structuredScheduleIntervalContainers.stream().sorted(Comparator.comparing(ScheduleIntervalContainer::getDateOfContainer))

.collect(Collectors.groupingBy(ScheduleIntervalContainer::getDateOfContainer, LinkedHashMap::new, Collectors.toList())).values());

but I am getting this error in eclipse:

The method sorted(Comparator<? super List<ScheduleIntervalContainer>>) in the type Stream<List<ScheduleIntervalContainer>> is not applicable for the arguments (Comparator<ScheduleIntervalContainer>)

网友答案:

You may sort the stream prior grouping, then use LinkedHashMap which preserves order:

List<List<MyType>> list = new ArrayList<> (
    myList.stream()
          .sorted(Comparator.comparing(MyType::getDateOfContainer))
          .collect(
              Collectors.groupingBy(MyType::getDateOfContainer,
                  LinkedHashMap::new,
                  Collectors.toList()))
          .values());
网友答案:

Stream has the sorted method which sort the elements. Take a look at the following example:

Stream.of(1,2,4,0,3).sorted().forEach(i -> System.out.println(i));

This will print

0
1
2
3
4

But in your case probably you will have to implement your own comparison method to sort the elements. Take a look at the following example I took from http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/

Stream.of("d2", "a2", "b1", "b3", "c")
      .sorted((s1, s2) -> {
          System.out.printf("sort: %s; %s\n", s1, s2);
          return s1.compareTo(s2);
      })
      .filter(s -> {
          System.out.println("filter: " + s);
          return s.startsWith("a");
      })
      .map(s -> {
          System.out.println("map: " + s);
          return s.toUpperCase();
      })
      .forEach(s -> System.out.println("forEach: " + s));
相关阅读:
Top