2015-05-26 36 views
28

Yeni akış API'sini daha iyi anlamak için bazı eski kodları dönüştürmeye çalışıyorum, ama buna takılıyorum.Java 8 Akış Toplama Seti

public Collection<? extends File> asDestSet() { 
    HashMap<IFileSourceInfo, Set<File>> map = new HashMap<IFileSourceInfo, Set<File>>(); 
    //... 
    Set<File> result = new HashSet<File>(); 
    for (Set<File> v : map.values()) { 
     result.addAll(v); 
    } 
    return result; 
} 

bunun için geçerli bir Collector oluşturmak gibi olamaz:

public Collection<? extends File> asDestSet() { 
    HashMap<IFileSourceInfo, Set<File>> map = new HashMap<IFileSourceInfo, Set<File>>(); 
    //... 
    return map.values().stream().collect(/* what? */); 
} 
+5

'dönüş map.values ​​() stream() flatMap (Set :: stream) .collect (Collectors.toSet());' veya '.collect (toCollection (HashSet :: new)); toSet() 'tarafından döndürülen set uygulamasının arkasında bir garanti yoktur. –

+2

veya '.collect (HashSet :: new, Set :: addAll, Set :: addAll)' – Misha

cevap

65

kullanın flatMap:

return map.values().stream().flatMap(Set::stream).collect(Collectors.toSet()); 

flatMap tek bir akışta setinizdeki tüm düzleşir.