Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the same items in a row in Java 8 Stream API

I have a bean and a stream

public class TokenBag {
    private String token;
    private int count;
    // Standard constructor and getters here
}
Stream<String> src = Stream.of("a", "a", "a", "b", "b", "a", "a");

and want to apply some intermediate operation to the stream that returns another stream of objects of TokenBag. In this example there must be two: ("a", 3), ("b", 3) and ("a", 2).

Please think it as a very simplistic example. In real there will be much more complicated logic than just counting the same values in a row. Actually I try to design a simple parser that accepts a stream of tokens and returns a stream of objects.

Also please note that it must stay a stream (with no intermediate accumulation), and also in this example it must really count the same values in a row (it differs from grouping).

Will appreciate your suggestions about the general approach to this task solution.

like image 733
Alex Avatar asked Jan 23 '26 10:01

Alex


1 Answers

Map<String, Long> result = src.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(result);

This will give the desired output

a=4, b=3

You can then go ahead and iterate over map and create objects of TokenBag.

like image 102
Rishikesh Dhokare Avatar answered Jan 25 '26 23:01

Rishikesh Dhokare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!