Since you are assigning the result to a List<List<String>> it appears you want to filter and sort each list and then print them. Here is how it might be done.
- Stream the list of lists.
- then stream each individual list and:
- then return that as a list
- and combine those lists into another list.
List<List<String>> sortedLists = list.stream() .map(lst -> lst.stream() .filter(o -> o.startsWith("A")) .sorted(Comparator.reverseOrder()).toList()) .toList(); for(List<String> lst : sortedLists) { System.out.println(lst); }
prints (given your data).
[Ann] [Andrew, Alex] [Adisson]
If, on the other hand you want to combine the lists into one applying the same requirements, then:
- stream the list of lists
- flatMap them to put all of the list contents into a single stream.
- then apply the filter and sort methods.
- and collect into a list.
List<String> sortedList = list.stream().flatMap(List::stream) .filter(o->o.startsWith("A")) .sorted(Comparator.reverseOrder()) .toList(); for (String name : sortedList) { System.out.println(name); }
prints
Ann Andrew Alex Adisson
List<String> sortedList = list.stream().flatMap(List::stream).filter(s -> s.startsWith("A")).sorted(Comparator.reverseOrder()).collect(Collectors.toList());