Giriş Döndürülen collection içindeki eleman sayısını verir
Stream.count() vs Collectors.counting()
Aslında her ikisi de aynı şeyi yapıyorlar.
Fark 1
Yani şu ikisi de aynı çıktıyı
verirSystem.out.println(Stream.of(1, 2, 3, 4, 5)
.map(i -> {
System.out.println("processing " + i);
return i * 2;
}).count());
System.out.println(Stream.of(1, 2, 3, 4, 5)
.map(i -> {
System.out.println("processing " + i);
return i * 2;
}).collect(Collectors.counting()));
Ama Stream.count() gerekirse, aradaki işlemleri atlayarak direkt sonuç dönebilir. Açıklaması
şöyle
An implementation may choose to not execute the stream pipeline (either sequentially or in parallel) if it is capable of computing the count directly from the stream source. In such cases no source elements will be traversed and no intermediate operations will be evaluated...
Fark 2
Collectors.counting() aslında gruplama için daha uygun. Şöyle
yaparızMap<String, Long> collect =
wordsList.stream().collect(groupingBy(Function.identity(), counting()));
Kullanım
Örnek
List<Integer> integers = Arrays.asList(1,2,3,4,5,6,6);
Long collect = integers
.stream()
.filter(x -> x < 4)
.collect(Collectors.counting());
// output: 3
Örnek
Elimizde bir sözcük listesi olsun. Listedeki sözcüklerin frekans tablosunu çıkarıp belli bir değerin üzerinde olan sözcüklerin sayısını şöyle
buluruz.
int countThreshold = 2;
long sum =
words.stream()
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()))
.values()
.stream()
.filter(x -> x >= countThreshold)
.reduce(0L, Long::sum);
Örnek
İki setin kesişimi kaç tane elemandan oluşur diye bulmak isteyelim. Şöyle
yaparız.
Set<String> sOne = ...; Set<String> sTwo = ...;
long numFound = sOne.parallelStream()
.filter(segment -> sTwo.contains(segment))
.collect(Collectors.counting());