How to convert two-dimensional Set / ArrayList object into one Flat Set / List using java 8

I am new to java 8, I have Set Set, for example:

Set<Set<String>> aa = new HashSet<>(); Set<String> w1 = new HashSet<>(); w1.add("1111"); w1.add("2222"); w1.add("3333"); Set<String> w2 = new HashSet<>(); w2.add("4444"); w2.add("5555"); w2.add("6666"); Set<String> w3 = new HashSet<>(); w3.add("77777"); w3.add("88888"); w3.add("99999"); aa.add(w1); aa.add(w2); aa.add(w3); 

EXPECTED RESULT: FLAT SET ... something like:

But that will not work!

 // HERE I WANT To Convert into FLAT Set // with the best PERFORMANCE !! Set<String> flatSet = aa.stream().flatMap(a -> setOfSet.stream().flatMap(ins->ins.stream().collect(Collectors.toSet())).collect(Collectors.toSet())); 

Any ideas?

+5
source share
2 answers

You only need to call flatMap :

 Set<String> flatSet = aa.stream() // returns a Stream<Set<String>> .flatMap(a -> a.stream()) // flattens the Stream to a // Stream<String> .collect(Collectors.toSet()); // collect to a Set<String> 
+11
source

As an alternative to @Eran's correct answer, you can use the collect 3 argument:

 Set<String> flatSet = aa.stream().collect(HashSet::new, Set::addAll, Set::addAll); 
+8
source

Source: https://habr.com/ru/post/1247333/


All Articles