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

วิธีใช้เมธอด collect() ใน Stream API ของ Java 9

เมธอด collect() ใน Stream API รวบรวม object ทั้งหมดจาก stream object เก็บใน type of collection ที่ผู้ใช้ระบุ ระบุ collection type ด้วย Collectors Enum มีหลายประเภทและ operation แต่ส่วนใหญ่ใช้ Collectors.toList() Collectors.toSet() และ Collectors.toMap()

ไวยากรณ์

<R, A> R collect(Collector<? super T, A, R> collector)

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

import java.util.*;
import java.util.stream.*;

public class StreamCollectMethodTest {
    public static void main(String args[]) {
        List<String> list = List.of("a", "b", "c", "d", "e", "f", "g", "h", "i");
        
        // takeWhile: เอาตั้งแต่ต้นจนกว่าเงื่อนไขจะเป็น true (Java 9+)
        List<String> subset1 = list.stream()
            .takeWhile(s -> !s.equals("e"))
            .collect(Collectors.toList());
        System.out.println(subset1);
        
        // dropWhile: ข้ามจนกว่าเงื่อนไขจะเป็น true แล้วเอาต่อไป (Java 9+)
        List<String> subset2 = list.stream()
            .dropWhile(s -> !s.equals("e"))
            .collect(Collectors.toList());
        System.out.println(subset2);
        
        // iterate: สร้าง stream จาก seed, predicate, function (Java 9+)
        List<Integer> numbers = Stream.iterate(1, i -> i <= 10, i -> i + 1)
            .collect(Collectors.toList());
        System.out.println(numbers);
    }
}

ผลลัพธ์

[a, b, c, d]
[e, f, g, h, i]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Collectors ที่ใช้บ่อย

Collectorคืนค่าคำอธิบาย
toList()List<T>สะสมเป็น ArrayList
toSet()Set<T>สะสมเป็น HashSet (ไม่ซ้ำ)
toCollection(Supplier)Collection<T>ระบุ collection implementation เอง
toMap(keyMapper, valueMapper)Map<K,V>สร้าง Map จาก key/value mappers
joining()Stringเชื่อม string ทั้งหมด
joining(delimiter)Stringเชื่อมด้วย delimiter
groupingBy(classifier)Map<K,List<T>>จัดกลุ่มตาม classifier
partitioningBy(predicate)Map<Boolean,List<T>>แบ่ง 2 กลุ่ม true/false

Java 9 Stream Methods ใหม่ที่ใช้กับ collect()

  • takeWhile(predicate) - เอา elements ตั้งแต่ต้นจนกว่า predicate จะ false
  • dropWhile(predicate) - ข้าม elements ตั้งแต่ต้นจนกว่า predicate จะ false แล้วเอาต่อ
  • iterate(seed, hasNext, next) - สร้าง finite stream (ต่างจาก iterate(seed, next) ที่ infinite)
  • ofNullable(value) - สร้าง stream 0 หรือ 1 element

collect() เป็น terminal operation ที่ทรงพลังที่สุดใน Stream API ร่วมกับ Collectors ทำได้หลากหลายรูปแบบ