4

This is my list:

List<Card> cards;

my Java-8 stream where i want to create the Map

Map<String, Integer> cardsMap = cards.stream().collect(Collectors.groupingBy(Card::getCardValue, amount of cards that are grouped));

This obviously doesn't work but i am clueless of how i would do it otherwise.

sansactions
  • 215
  • 5
  • 17

2 Answers2

7

Is this what you meant?

    Map<String, Long> cardsMap = cards
            .stream()
            .collect(Collectors.groupingBy(Card::getCardValue, Collectors.counting()));

It will give you a map from card values to counts of cards with that value in your original list. For example, if you have:

    List<Card> cards = Arrays.asList(new Card("4"), new Card("8"), new Card("4"));

(and I know I’ve probably reduced your Card() constructor), the above will map "4" to 2 and "8" to 1.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
2

This is how to do it:

Map<String, Long> cardsMap = cards.stream().collect(Collectors.groupingBy(e -> e.getCardValue(), Collectors.counting()));

Here are more ways: How to count the number of occurrences of an element in a List

Austin
  • 2,982
  • 2
  • 28
  • 36
sansactions
  • 215
  • 5
  • 17