2016-04-18 21 views
5

Tôi mới trong java 8, tôi đã thiết lập các Set ví dụ:Làm thế nào để Chuyển đổi hai đối tượng chiều Set/ArrayList vào một Flat Set/Danh sách sử dụng 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); 

KẾT QUẢ DỰ KIẾN: SET FLAT. ..cái gì đó như:

Nhưng nó không hoạt động!

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

Bất kỳ ý tưởng nào?

Trả lời

11

Bạn chỉ cần gọi flatMap một lần:

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

Và bạn không cần ' setOfSet'. Chỉ cần phát 'aa'. – shmosel

+2

@shmosel Điểm tốt – Eran

+0

Cảm ơn @Eran! . – VitalyT

8

Để thay thế cho @ câu trả lời đúng Eran, bạn có thể sử dụng 3 đối số collect:

Set<String> flatSet = aa.stream().collect(HashSet::new, Set::addAll, Set::addAll); 
Các vấn đề liên quan