0

I want to output all names starting with the letter "A" and sort them in reverse alphabetical order using the Stream API. The result should look like this: Ann, Andrew, Alex, Adisson. How do I do this?

List<List<String>> list = Arrays.asList( Arrays.asList("John", "Ann"), Arrays.asList("Alex", "Andrew", "Mark"), Arrays.asList("Neil", "Adisson", "Bob") ); List<List<String>> sortedList = list.stream() .filter(o -> o.startsWith("A")) Comparator.reverseOrder()); System.out.println(list); 
1
  • 2
    List<String> sortedList = list.stream().flatMap(List::stream).filter(s -> s.startsWith("A")).sorted(Comparator.reverseOrder()).collect(Collectors.toList()); Commented Jul 4, 2022 at 20:26

1 Answer 1

3

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 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.