Đếm số element trong stream dùng phương thức counting() của Java Streams.
Ví dụ 1: Stream String
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
public static void main(String[] args) {
Stream<String> stream = Stream.of("Kevin", "Jofra", "Tom", "Chris", "Liam");
long count = stream.collect(Collectors.counting());
System.out.println("Số element trong stream = " + count);
}
}
Kết quả
Số element trong stream = 5
Ví dụ 2: Stream Integer
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
public static void main(String[] args) {
Stream<Integer> stream = Stream.of(5, 10, 20, 40, 80, 160);
long count = stream.collect(Collectors.counting());
System.out.println("Số element trong stream = " + count);
}
}
Kết quả
Số element trong stream = 6
Mẹo: Có thể dùng stream.count() trực tiếp (terminal operation) thay cho collect(Collectors.counting()) ngắn gọn hơn. counting() hữu ích khi dùng như downstream collector trong groupingBy, partitioningBy.