Reduce a HashMap to another HashMap

I start of with a string like this:

"train, Train, bike, BIKE, car...etc"

of travel types, and need to return a HashMap<String, Integer>(), such as this:

(train, 4), (car, 6), (bike, 2)

The number indicates the amount of times that travel type has been seen

This is as far as I’ve got, mapping the string into a initial hashmap like this:

(train, 1), (train, 1), (car, 1), (car, 1)...etc

with:

public static HashMap<String, Integer> countTravelTypes(String travelTypes) {
    return Arrays.stream(travelTypes.toLowerCase().replace(" ", "")
            .split(","))
            .map(s -> new HashMap<String, Integer>(){{put(s, 1);}})
            //The line below isn't right but it's as close as I could get
            .reduce(0, map -> map.key, Integer.sum(v))
}

Can you help me with the reduction of it now, so basically summing up all the trains to show there were 4

Answer

We can use Collectors.summingInt() for an output Map of type Map<String, Integer> :

Map<String, Integer> result =  
Stream.of("train, Train, bike, BIKE, car, BIKE, Train".split(", "))
      .collect(Collectors.groupingBy(i -> i, Collectors.summingInt(i -> 1)));

Leave a Reply

Your email address will not be published. Required fields are marked *