Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Stream: How to Sum Value If Element Already Exists

Given the following key…

private class PositionKey {
    String assetId;
    String currencyId;
}

… I need to create a Map<PositionKey, BigDecimal>, where if a given key does not exist, then a new entry shall be added, otherwise, if a given key already exists, then its values shall be increased. Here below is my attempt:

public Map<PositionKey, BigDecimal> getMap(final Long portfolioId) {

    final Map<PositionKey, BigDecimal> map = new HashMap<>();

    // getPositions() returns all the positions associated with the given portfolio
    return getPositions(portfolioId).stream()
        .collect(
            toMap(
                position ->
                    new PositionKey(
                        position.getAssetId(),
                        position.geCurrencyId()),
                position -> position.geValue(),
                (newValue, oldValue) -> oldValue != null ? oldValue.add(newValue) : newValue,
                () -> map));
}

What I dislike in my implementation above, is the fact that I create the Map before streaming the positions. Is there a better way to implement this? Thank you very much.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

simple! replace () -> map with either () -> new HashMap<>() or HashMap::new

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading