0

i've been trying to figure out how to use java 8 streams to create a map like the one created by getCardValueCountMap method below:

public class Hand {
        private final List<Card> hand = new ArrayList<>();
        .....
        public Map<CardValue, Integer> getCardValueCountMap(){
            HashMap<CardValue, Integer> cardValueCountMap = new HashMap<>();
            for (Card card : hand) {
                final CardValue value = card.getValue();
                Integer count = cardValueCountMap.get(value);
                if (count == null){
                   cardValueCountMap.put(value, 1);
                } else {
                   cardValueCountMap.put(value, count + 1);
                }
            }
            return cardValueCountMap;
         }
....
}
richs
  • 4,699
  • 10
  • 43
  • 56

1 Answers1

2

This doesn't use streams, so isn't really an answer to your question, but in my opinion the cleanest way to do this is to take advantage of the improvements to the Map interface.

HashMap<CardValue, Integer> map = new HashMap<>();
for (Card card : hand)
    map.merge(card.getValue(), 1, Integer::sum);
Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
  • 2
    I like that. Alternatives: `hand.stream().collect(toMap(Card::getValue, c -> 1, Integer::sum));` -- `hand.stream().collect(groupingBy(Card::getValue, counting()));`. – Tunaki Apr 11 '16 at 17:10