I have an ordered list of Strings, let's say "aaa", "aaa", "aaa", "bbb", "bbb", "aaa"
. I would like to group adjacent equal strings together and count them, so the result of the operation should be a List
looking like this: {"aaa":3}, {"bbb":2}, {"aaa", 1}
. Note that the task is not to just group by the same values and count them (otherwise I could simply use groupingBy
with counting
), but group by only adjacent strings with the same value, and if the same string appears later in the list then it should be considered as separate. Basically, I need this piece of code to create a table header with appropriate colspans out of an existing data structure.
I'd like to know if there's a reasonably good way to achieve this task using Java 8 streams. I know how to do it using an old-school loop, just thought maybe streams provide a better way.