Wayneio
Wayneio

Reputation: 3566

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

Upvotes: 2

Views: 179

Answers (2)

Fullstack Guy
Fullstack Guy

Reputation: 16908

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)));

Upvotes: 3

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

You may use groupingBy collector in concert with the counting downstream collector to get this thing done. Here's how it looks.

Map<String, Long> result = Arrays.stream(source.split(","))
    .map(String::trim)
    .map(String::toLowerCase)
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

Upvotes: 3

Related Questions