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 = -> 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 =

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.
     .mapToLong(i -> i/2)

This returns 2 for the sample input.

I got it to work by using Collectors.summingInt:

Integer result = groups.entrySet()
    .collect(Collectors.summingInt(x -> x.getValue().size() / 2)
Most efficient way to increment a Map value in Java
Fastest way to determine if an integer's square root is an integer
A Java collection of value pairs? (tuples?)
'Must Override a Superclass Method' Errors after importing a project into Eclipse
list comprehension vs. lambda + filter
How to update a value, given a key in a hashmap?
How to add local jar files to a Maven project?
Retrieving a List from a in Java 8
Java 8 List<V> into Map<K, V>
Java List<Map<String, Long>> sum of group by of map key