Home > Mobile >  List of object to map group by object property
List of object to map group by object property

Time:12-17

I have a list of Object where some amount along with GL Head. I want to make a Map of the group sum of those amount by GL-Head.

            List<Fees> feesList = new ArrayList<>();
            Fees f = new Fees();
            f.setGlHead(10);
            f.setImposed(25.0);
            feesList.add(f);

            f = new Fees();
            f.setGlHead(11);
            f.setImposed(30.0);
            feesList.add(f);

            f = new Fees();
            f.setGlHead(10);
            f.setImposed(15.0);
            feesList.add(f);

            Map<Integer, Double> map = ..... // how by lambda ?

Where, Key integer is The GL Head, Value Double is group sum of Imposed amount by GL Head and result like a map with values >> (10, 40.0) & (11, 30)

CodePudding user response:

Streams to the rescue! This task is essentially one of the examples in the Collectors documentation, just with doubles instead of ints.

var map = feesList.stream()
           .collect(Collectors.groupingBy(Fees::getGlHead,
                                          Collectors.summingDouble(Fees::getImposed));

(Adjust as needed for the actual method names)


If you don't want to use streams, you can get the same effect with a loop:

var map = new HashMap<Integer, Double>(); // Or whatever type of map
for (Fees fee : feeList) {
    map.merge(fee.getG1Head(), fee.getImposed(), Double::sum);
}

The Map::merge function will, if a given key doesn't already exist in the map, add it with the given value. If the key already exists, the new value and the existing one are passed to the function that is the third argument, and the map updated with its result.

CodePudding user response:

Map<Integer, Double> map = feesList.stream().collect(Collectors.toMap(Fees::getGlHead, Fees::getImposed));

you can use stream(),but based on your example,you will get a IllegalStateException,cause Duplicate key 10.

  • Related