0

So I have the following class and the ArrayList of objects:

class Ticket{
    String destination;
}

ArrayList<Ticket> tickets;

What I want is to get from my list a Map of String and Integer which contains the destinations from tickets and the number of occurences in my list for each destination. I think it would start like this, but I don't know how to continue:

Map<String,Integer> map=tickets.stream().filter(a->a.getDestination()).
CanciuCostin
  • 1,773
  • 1
  • 10
  • 25

2 Answers2

2

You can use a combination of a groupingBy collector and the summingInt collector like this:

Map<String,Integer> map = 
  tickets.stream()
         .collect(Collectors.groupingBy(Ticket::getDestination, 
                   Collectors.summingInt(e -> 1)));

In this case, I've specifically used the summingInt collector due to the fact that the counting() collector returns a Long type and since you want the map values as Integer's then the summingInt collector is the most appropriate.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
2

Use the groupingBy collector.

tickets.stream().collect(Collectors.groupingBy(Ticket::getDestination,
        Collectors.counting()));

This will give you a Map<String, Long>.

If you want a map with Integer values, you can replace counting with a summingInt that simply returns 1 (which is what this answer does)

Salem
  • 13,516
  • 4
  • 51
  • 70