Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ความสำคัญของเมธอด Collectors.flatMapping() ใน Java 9

ใน Java 9 เพิ่มเมธอดใหม่ในคลาส Collectors: flatMapping() คล้ายกับ Collectors.mapping() แตกต่างตรงที่ flatMapping() จัดการ nested collections ได้ เมธอด Collectors.flatMapping() รับ function สำหรับแปลง input elements และ collector สำหรับสะสม elements ที่ผ่าน function ไป ต่างจาก Collectors.mapping() ที่ flatMapping() จัดการกับ stream of elements ช่วยกำจัด intermediate collections ที่ไม่จำเป็น

ไวยากรณ์

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

ตัวอย่างการใช้งาน

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

ผลลัพธ์

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

คำอธิบายตัวอย่าง

  1. Stream ของ 2 Lists: [1,2,3,4,5,6] (size 6) และ [7,8,9,10] (size 4)
  2. groupingBy ตาม Collection::size → 2 groups: size 6 และ size 4
  3. flatMapping: แต่ละ list → stream → filter เฉพาะเลขคู่ → collect toList
  4. ผลลัพธ์: size 6 → [2,4,6], size 4 → [8,10]

ความแตกต่าง mapping() vs flatMapping()

เมธอดFunction คืนค่าDownstream ได้รับ
mapping()U (single element)Element เดียวต่อ input
flatMapping()Stream<U> (stream of elements)หลาย elements ต่อ input (flatten)

เมื่อไหร่ควรใช้ flatMapping()

  • Input element คือ collection/array ที่ต้องการ flatten
  • ต้องการแปลง 1 input เป็นหลาย output elements
  • ร่วมกับ groupingBy, partitioningBy เพื่อ flat nested structures

flatMapping() ทำให้ Stream collector ทรงพลังมากขึ้น จัดการ nested data structures ได้โดยตรง