Java 8 Stream Filer based on Object property

ging :

I am trying to get the sum of all values from a map using streams in java 8. Below is the Collection i have:

Map<BigDecimal, List<Object>> map = ...... //some elements in this map

Lets say Object has below properties:

BigDecimal previousAmount;
int typeCode;

I am trying to get the sum of all previousAmount for each object in a list for all keys. Below is what i have came up with:

BigDecimal previousAmt = map.values().stream().flatMap(List::stream)
            .map(Object::previousAmount).reduce(BigDecimal.ZERO, (a, b) -> a.add(b));

This is giving me the sum of all elements in the list and for all keys correctly. But i am trying to filter and get the sum only if the typeCode is greater than 10.

Can any one please suggest how to filter the above stream using typeCode?

Samuel Philipp :

You can just use the Stream.filter() method:

BigDecimal previousAmt = map.values().stream().flatMap(List::stream)
    .filter(i -> i.getTypeCode() > 10) // filters the stream
    .map(MyObject::getPreviousAmount)
    .reduce(BigDecimal.ZERO, BigDecimal::add);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=151135&siteId=1