Counting

Counting the number of words in a piece of text is a common problem that can be solved by count():

String str = "Lorem Ipsum is simply dummy text ...";

long numberOfWords = Stream.of(str)
.map(w -> w.split("\s+"))
.flatMap(Arrays::stream)
.filter(w -> w.trim().length() != 0)
.count();

But let's see how many Melon weighing 3,000  there are in our stream:

long nrOfMelon = melons.stream()
.filter(m -> m.getWeight() == 3000)
.count();

We can use the collector that's returned by the counting() factory method:

long nrOfMelon = melons.stream()
.filter(m -> m.getWeight() == 3000)
.collect(Collectors.counting());

We can also use the clumsy approach of using reducing():

long nrOfMelon = melons.stream()
.filter(m -> m.getWeight() == 3000)
.collect(Collectors.reducing(0L, m -> 1L, Long::sum));
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.41.205