3

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
  • 195
  • 3
  • 16

2 Answers2

6

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.
  • 76,217
  • 14
  • 120
  • 142
1

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,524
  • 2
  • 24
  • 34
sansactions
  • 195
  • 3
  • 16