If you're open to using a third-party library, you can use the Collectors2
class in Eclipse Collections to convert the List
to a Bag
using a Stream
. A Bag
is a data structure that is built for counting.
Bag<String> counted =
list.stream().collect(Collectors2.countBy(each -> each));
Assert.assertEquals(1, counted.occurrencesOf("World"));
Assert.assertEquals(2, counted.occurrencesOf("Hello"));
System.out.println(counted.toStringOfItemToCount());
Output:
{World=1, Hello=2}
In this particular case, you can simply collect
the List
directly into a Bag
.
Bag<String> counted =
list.stream().collect(Collectors2.toBag());
You can also create the Bag
without using a Stream
by adapting the List
with the Eclipse Collections protocols.
Bag<String> counted = Lists.adapt(list).countBy(each -> each);
or in this particular case:
Bag<String> counted = Lists.adapt(list).toBag();
You could also just create the Bag directly.
Bag<String> counted = Bags.mutable.with("Hello", "Hello", "World");
A Bag<String>
is like a Map<String, Integer>
in that it internally keeps track of keys and their counts. But, if you ask a Map
for a key it doesn't contain, it will return null
. If you ask a Bag
for a key it doesn't contain using occurrencesOf
, it will return 0.
Note: I am a committer for Eclipse Collections.