Streams Intermédiaire

Utilisez flatMapping() pour aplatir à l'intérieur d'un collector de regroupement.

✕ Java 8
// Flatten within a grouping collector
// Required complex custom collector
Map<String, Set<String>> tagsByDept =
    // no clean way in Java 8
✓ Java 9+
var tagsByDept = employees.stream()
    .collect(groupingBy(
        Emp::dept,
        flatMapping(
            e -> e.tags().stream(),
            toSet()
        )
    ));
Un problème avec ce code ? Dites-le nous.
🧩

Composable

Fonctionne comme collector descendant à l'intérieur de groupingBy.

📐

Un seul passage

Aplatit et regroupe en un seul parcours du stream.

🔗

Imbriquable

Se combine avec d'autres collectors descendants.

Ancienne Approche
flatMap imbriqué
Approche Moderne
flatMapping()
Depuis JDK
9
Difficulté
Intermédiaire
Collectors.flatMapping()
Disponible

Disponible depuis JDK 9 (sept. 2017)

Collectors.flatMapping() applique un mapping un-à-plusieurs comme un collector descendant. C'est l'équivalent dans les collectors de Stream.flatMap() — utile à l'intérieur de groupingBy ou partitioningBy.

Partager 𝕏 🦋 in