0

Is there any possibility to convert a List of Set to Set using java 8 streams. Here my List :

// Get Header Columns to display in EXCEL FILE

    List<Set<String>> keysQuery = listExtractQglobal.parallelStream()
                    .map(m -> m.keySet()).distinct().collect(Collectors.toList()); 

Thanks

2
  • What's the type of listExtractQglobal variable? Commented Mar 25, 2021 at 12:32
  • List of Map : List<Map<String, Object>> Commented Mar 25, 2021 at 13:07

3 Answers 3

2

Just use a flatMap

Set<String> a = keysQuery.stream().flatMap(s -> s.stream()).collect(Collectors.toSet());

As the comment indicated you can also replace the lambda function with lambda reference

 Set<String> a = keysQuery.stream().flatMap(Set::stream).collect(Collectors.toSet());
Sign up to request clarification or add additional context in comments.

2 Comments

Or using a method reference: .flatMap(Set::stream).
@JavaProgramer please accept the answer if the problem is solved
0

Assuming this is how you create your list:

List<Set<String>> keysQuery = listExtractQglobal.parallelStream()
                    .map(m -> m.keySet()).distinct().collect(Collectors.toList());

you can actually avoid unnecessary collecting to a list and collect to a set instead:

Set<String> keysQuery = listExtractQglobal.parallelStream()
                                          .map(Map::keySet)
                                          .distinct()
                                          .flatMap(Collection::stream)
                                          .collect(Collectors.toSet());

Btw, I'm not sure why do you need the distinct here. Are you looking for distinct sets or distinct keys among all key sets? In latter case you could simply omit the distinct(), since the resulting Set contains distinct values by definition:

Set<String> keysQuery = listExtractQglobal.parallelStream()
                                          .map(Map::keySet)
                                          .flatMap(Collection::stream)
                                          .collect(Collectors.toSet());

Comments

0

I would use Stream#mapMulti from instead of Stream#flatMap as it has an overhead of possibly creating empty or very small streams

Set<String> keysQuery = listExtractQglobal.parallelStream()
                                          .map(Map::keySet)
                                          .mapMulti((Set<String> set, Consumer<String> consumer) -> {
                                              set.forEach(consumer::accept);
                                          })
                                          .collect(Collectors.toSet()); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.