Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Tầm quan trọng của Collectors.flatMapping() trong Java 9

Java 9 thêm Collectors.flatMapping() – tương tự Collectors.mapping() nhưng xử lý nested collections. Cho phép function trả về Stream thay vì single value, loại bỏ intermediate collection không cần thiết.

Cú pháp

public static <T,U,A,R> Collector<T,?,R> flatMapping(
    Function<? super T, ? extends Stream<? extends U>> mapper,
    Collector<? super U, A, R> downstream)

Ví dụ: Group by collection size, flatMap even numbers

import java.util.stream.Collectors;
import java.util.Stream;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class FlatMappingMethodTest {
    public static void main(String args[]) {
        Map<Integer, List<Integer>> map = Stream.of(
                List.of(1, 2, 3, 4, 5, 6),
                List.of(7, 8, 9, 10))
            .collect(Collectors.groupingBy(
                Collection::size,
                Collectors.flatMapping(
                    l -> l.stream().filter(i -> i % 2 == 0),
                    Collectors.toList()
                )
            ));
        System.out.println(map);
    }
}

Kết quả

{4=[8, 10], 6=[2, 4, 6]}

Giải thích

  • Stream 2 List: size 6 và size 4.
  • groupingBy(Collection::size): Group theo size (key 6, 4).
  • flatMapping(l -> l.stream().filter(i -> i%2==0), toList()):
    • Mỗi List → stream → filter even numbers.
    • Flatten thành single stream của even numbers.
    • Collect thành List cho mỗi group.
  • Kết quả: Group size 6 → [2,4,6], Group size 4 → [8,10].

flatMapping vs mapping

Đặc điểmmapping()flatMapping()
Mapper trả vềSingle value (U)Stream<U>
Xử lý nested collectionKhó (cần flatMap trước)Trực tiếp, tự flatten
Intermediate collectionCó thể tạo raTránh được
Use case1-1 mapping1-N mapping (collection → elements)

Ví dụ thực tế: Tách từ thành ký tự

List<String> words = List.of("Hello", "World");
Map<Integer, List<Character>> charGroups = words.stream()
    .collect(Collectors.groupingBy(
        String::length,
        Collectors.flatMapping(
            w -> w.chars().mapToObj(c -> (char)c),
            Collectors.toList()
        )
    ));
// {5=[H, e, l, l, o, W, o, r, l, d]}

flatMapping() làm Collector API mạnh mẽ hơn cho nested data transformation.