Phương thức toCollection() của lớp Collectors trong Java trả về Collector tích lũy input elements vào Collection mới theo thứ tự gặp (encounter order).
Cú pháp
static <T,C extends Collection<T>> Collector<T,?,C> toCollection(Supplier<C> collectionFactory)
T- kiểu input elementsC- kiểu Collection kết quảSupplier- cung cấp instance Collection mới, rỗng, kiểu phù hợp
Ví dụ 1: Stream String to TreeSet
import java.util.Collection;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
public static void main(String[] args) {
Stream<String> stream = Stream.of("25", "10", "15", "20", "25");
Collection<String> collection = stream.collect(Collectors.toCollection(TreeSet::new));
System.out.println("Collection = " + collection);
}
}
Kết quả
Collection = [10, 15, 20, 25]
TreeSet tự động loại trùng và sắp xếp tự nhiên (lexicographical cho String).
Ví dụ 2: Stream String to TreeSet (tên người)
import java.util.Collection;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
public static void main(String[] args) {
Stream<String> stream = Stream.of("Jack", "Tom", "Brad", "Tim", "Kevin", "Bradley", "Ryan");
Collection<String> collection = stream.collect(Collectors.toCollection(TreeSet::new));
System.out.println("Collection = " + collection);
}
}
Kết quả
Collection = [Brad, Bradley, Jack, Kevin, Ryan, Tim, Tom]
Ứng dụng: Dùng toCollection(ArrayList::new), toCollection(LinkedList::new), toCollection(HashSet::new), toCollection(() -> new TreeSet<>(comparator)) để tùy biến collection kết quả.