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.
>Solution :
simple! replace () -> map with either () -> new HashMap<>() or HashMap::new