Java 스트림 counting() 메서드를 사용하여 스트림의 요소 수를 계산합니다. 다음은 Java Streams counting() 메서드를 구현하는 예입니다. -
예시
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");
// count
long count = stream.collect(Collectors.counting());
System.out.println("Number of elements in the stream = "+count);
}
} 출력
Number of elements in the stream = 5
정수 요소의 스트림이 있는 또 다른 예를 살펴보겠습니다. -
예시
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);
// count
long count = stream.collect(Collectors.counting());
System.out.println("Number of elements in the stream = "+count);
}
} 출력
Number of elements in the stream = 6