Skip to content

Commit

Permalink
Implement countBy on Collectors2.
Browse files Browse the repository at this point in the history
Signed-off-by: Donald Raab <Donald.Raab@bnymellon.com>
  • Loading branch information
donraab committed Sep 27, 2017
1 parent 305b981 commit d593a1b
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
Expand Up @@ -721,6 +721,21 @@ private Collectors2()
EMPTY_CHARACTERISTICS);
}

/**
* Returns the counts of all of the values returned by applying the specified function to each
* item of the Stream.
*
* @since 9.1
*/
public static <T, K> Collector<T, ?, MutableBag<K>> countBy(Function<? super T, ? extends K> function)
{
return Collector.of(
Bags.mutable::empty,
(bag, each) -> bag.with(function.valueOf(each)),
MutableBag::withAll,
EMPTY_CHARACTERISTICS);
}

/**
* <p>Returns the elements as an MutableMultimap grouping each element using the specified groupBy Function.</p>
* <p>Examples:</p>
Expand Down
Expand Up @@ -16,6 +16,7 @@
import java.util.Map;
import java.util.stream.Collectors;

import org.eclipse.collections.api.bag.MutableBag;
import org.eclipse.collections.api.collection.primitive.MutableIntCollection;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.api.map.primitive.MutableObjectLongMap;
Expand Down Expand Up @@ -1083,4 +1084,24 @@ public void toImmutableBagMultimap2Parallel()
LARGE_INTERVAL.reduceInPlace(Collectors2.toImmutableBagMultimap(Object::toString, Object::toString)),
this.bigData.parallelStream().collect(Collectors2.toImmutableBagMultimap(Object::toString, Object::toString)));
}

@Test
public void countBy()
{
Interval integers = Interval.oneTo(100);
MutableBag<Integer> counts = integers.stream().collect(Collectors2.countBy(i -> i % 2));
Assert.assertEquals(integers.countBy(i -> i % 2), counts);
Assert.assertEquals(50, counts.occurrencesOf(0));
Assert.assertEquals(50, counts.occurrencesOf(1));
}

@Test
public void countByParallel()
{
Interval integers = Interval.oneTo(100000);
MutableBag<Integer> counts = integers.parallelStream().collect(Collectors2.countBy(i -> i % 2));
Assert.assertEquals(integers.countBy(i -> i % 2), counts);
Assert.assertEquals(50000, counts.occurrencesOf(0));
Assert.assertEquals(50000, counts.occurrencesOf(1));
}
}

0 comments on commit d593a1b

Please sign in to comment.