2016-04-18 3 views
5

Ich bin neu in Java 8, ich habe zum Beispiel von Set Set:Wie zwei Objekt Dimension konvertieren Set/Arraylist in eine Wohnung Set/Liste java 8

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); 

Erwartetes Ergebnis: FLAT SET. ..etwas wie:

Aber es funktioniert nicht!

// 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())); 

Irgendwelche Ideen?

Antwort

11

Sie müssen nur flatMap einmal nennen:

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> 
+2

Und Sie brauchen nicht ' setOfSet' überhaupt. Strömen Sie einfach 'aa'. – shmosel

+2

@shmosel Guter Punkt – Eran

+0

Danke @Eran! . – VitalyT

8

Als Alternative zu @ Eran die richtige Antwort, können Sie das 3-Argument verwenden collect:

Set<String> flatSet = aa.stream().collect(HashSet::new, Set::addAll, Set::addAll); 
Verwandte Themen