Learning through exercises
- space: next page
- down arrow: next page in the current section
- right arrow: next section
- A
Bag
of randomized instances of typeCandy
is generated by invokingSchoolGroup.trickOrTreat()
- down: New concepts for Candy Kata Test
- right: Candy Kata Test solutions
- Belong to the set of methods of the
Bag
interface topOccurrences(int count)
returns thecount
most frequently occuring items (e.g.topOccurrences(2)
returns the top 2 most reoccuring items inside the bag).- Similarly,
bottomOccurrences(int count)
returns thecount
least frequently occuring items. - If there is a tie among the items which qualify, the logic is inclusive and will include all items whose occurrences match the occurrences of the last item.
MutableBag<Candy> bag =
Bags.mutable.with(Candy.CRUNCH, Candy.HERSHEYS, Candy.HERSHEYS,
Candy.HERSHEYS, Candy.MOUNDS, Candy.CRUNCH);
ImmutableList<ObjectIntPair<Candy>> expectedNoTies =
Lists.immutable.with(PrimitiveTuples.pair(Candy.HERSHEYS, 3),
PrimitiveTuples.pair(Candy.CRUNCH, 2));
Assertions.assertEquals(expectedNoTies, bag.topOccurrences(2));
bag.add(Candy.MOUNDS);
// The top 2 occurrences actually now includes 3 since there was a tie
// The expected output is converted to a Set to ignore ordering
Set<ObjectIntPair<Candy>> expectedTie = expectedNoTies.toSet()
.with(PrimitiveTuples.pair(Candy.MOUNDS, 2));
Assertions.assertEquals(expectedTie, bag.topOccurrences(2).toSet());
- Fix
CandyKataTest
; there are failing tests. - Use topOccurrences()
- down: Exercise solutions
@Test
public void topCandy()
{
MutableList<Bag<Candy>> bagsOfCandy = this.collectBagsOfCandy();
Bag<Candy> bigBagOfCandy =
bagsOfCandy.flatCollect(bag -> bag).toBag();
MutableSet<Candy> mostCommon =
bigBagOfCandy.topOccurrences(1)
.collect(ObjectIntPair::getOne)
.toSet();
var expectedSet = Sets.mutable.with(Candy.REESES_PIECES);
Assert.assertEquals(expectedSet, mostCommon);
}
@Test
public void commonInTop10()
{
MutableList<Bag<Candy>> bagsOfCandy = this.collectBagsOfCandy();
MutableSet<Candy> commonInTop10 =
bagsOfCandy.collect(
bag -> bag.topOccurrences(10)
.collect(ObjectIntPair::getOne)
.toSet())
.reduce(MutableSet::intersect)
.get();
var expectedSet = Sets.mutable.with(Candy.REESES_PIECES, Candy.CRUNCH);
Assert.assertEquals(expectedSet, commonInTop10);
}
You have completed the Candy Kata!
Enjoy happy Java development with Eclipse Collections!