The Occurrences of Occurrences

Keeping counts, and letting you use them for different purposes.

Image for post
Image for post
Part of my shot glass collection
Image for post
Image for post
The method collectWithOccurrences is the newest addition in 9.1.
@Test
public void topOccurrencesOfOccurrences()
{
Lists.fixedSize.with(MutableBag.class.getMethods())
.asLazy()
.selectWith(this::methodContains, "occurrences")
.countBy(Method::getName)
.topOccurrences(4)
.each(System.out::println);
}

private boolean methodContains(Method method, String string)
{
return method.getName().toLowerCase().contains(string);
}
selectByOccurrences:4
topOccurrences:2
bottomOccurrences:2
forEachWithOccurrences:1
setOccurrences:1
addOccurrences:1
occurrencesOf:1
collectWithOccurrences:1
removeOccurrences:1
@Test
public void collectWithOccurrences()
{
Bag<ShotGlass> glasses = Bags.mutable.with(
new ShotGlass(Size.SMALL, "Orlando", "Florida", "USA",
"Disney World"),
new ShotGlass(
Size.SMALL, "Orlando", "Florida", "USA",
"Sea World"),
new ShotGlass(
Size.SMALL, "Orlando", "Florida", "USA",
"Universal Studios"),
new ShotGlass(
Size.MEDIUM, "Orlando", "Florida", "USA",
"Hard Rock Cafe")
);

Bag<String> byCity = glasses.countBy(ShotGlass::getCity);

Assert.assertEquals(
Bags.mutable.with(PrimitiveTuples.pair("Orlando", 4)),
byCity.collectWithOccurrences(
PrimitiveTuples::pair, Bags.mutable.empty()));

Bag<Size> bySize = glasses.countBy(ShotGlass::getSize);

Assert.assertEquals(
Bags.mutable.with(
PrimitiveTuples.pair(Size.SMALL, 3),
PrimitiveTuples.pair(Size.MEDIUM, 1)),
bySize.collectWithOccurrences(
PrimitiveTuples::pair, Bags.mutable.empty()));
}

Java Champion. Creator of the Eclipse Collections OSS Java library (http://www.eclipse.org/collections/). Inspired by Smalltalk. Opinions are my own.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store