# LaVOZs

The World’s Largest Online Community for Developers

'; java - perform projection on list - LavOzs.Com

I have a list of numbers that I group by the number of occurences. E.g. my list is `{ 1, 2, 1, 1, 2, 3 }` the grouped list would look like this:

``````{
{ Key = 1, Value = { 1, 1, 1 } },
{ Key = 2, Value = { 2, 2 } },
{ Key = 3, Value = { 3 } }
}
``````

Here´s the code for that grouping:

``````Map<Integer, List<Integer>> groups = input.stream().collect(Collerctors.groupingBy(x -> x));
``````

Now for each of those groups I want to get pairs. So for `1` there´s only one pair, the last `1` is omitted. For `2` we also have a single pair, for `3` we don´t have any. So I thought of getting the size of every group and devide it by 2. Finally I need to sum all those results. However I have no idea how to perform such a projection in java. In C# I would do something like this:

``````var result = groups.Select(x => x.ToList().Count / 2).Sum();
``````

I suppose in Java I´d use the `collect`-function, but I couldn´t get it:

``````Integer result = groups.stream().collect(...)
``````

First of all, you can chain a `counting` `Collector` to `groupingBy`, so that the values of the `Map` will be the number of elements of each group.

Then you can `Stream` over the values, divide by 2, and compute the sum.

``````input.stream()
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))
.values()
.stream()
.mapToLong(i -> i/2)
.sum();
``````

This returns `2` for the sample input.

I got it to work by using `Collectors.summingInt`:

``````Integer result = groups.entrySet()
.stream()
.collect(Collectors.summingInt(x -> x.getValue().size() / 2)
``````