Java 8 Stream Collecting Set

Lesezeit: 1 Minute

Um die neue Stream-API besser zu verstehen, versuche ich, alten Code zu konvertieren, aber ich stecke bei diesem fest.

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

Ich kann anscheinend keinen gültigen Collector dafür erstellen:

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

  • return map.values().stream().flatMap(Set::stream).collect(Collectors.toSet()); oder .collect(toCollection(HashSet::new)); da hinter der von zurückgesendeten Set-Umsetzung keine Garantie steht toSet().

    – Alexis C.

    26. Mai 2015 um 17:18 Uhr


  • oder .collect(HashSet::new, Set::addAll, Set::addAll)

    – Mischa

    26. Mai 2015 um 20:55 Uhr


Benutzer-Avatar
Tagir Walejew

Verwenden flachKarte:

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

Das flatMap glättet alle Ihre Sets in einem einzigen Stream.

1159540cookie-checkJava 8 Stream Collecting Set

This website is using cookies to improve the user-friendliness. You agree by using the website further.

Privacy policy