Jackie
Jackie

Reputation: 23527

How do I use Java stream collect to create a map with a String as the key instead of object?

I have the following...

public Map<Object, Integer> getRankings(){
    Stream<String> stream = votes.stream();
    Map<Object, Integer> map = stream
            .collect(Collectors.toMap(s -> s, s -> 1, Integer::sum));
    return Vote.sortByValues(map);
}

But I would like the return type to be Map<String, Integer> instead. How do I coerce the Object to a String?

Upvotes: 0

Views: 75

Answers (2)

Marco Dalla Santa
Marco Dalla Santa

Reputation: 361

There's no problem in this:

public Map<String, Integer> getRankings(){
    Stream<String> stream = votes.stream();
    Map<String, Integer> map = stream
            .collect(Collectors.toMap(s -> s, s -> 1, Integer::sum));
    return Vote.sortByValues(map);
}

Upvotes: 1

Mureinik
Mureinik

Reputation: 311326

Since you have a Stream<String>, it can be inferred by just declaring the map with a key type of String:

Map<String, Integer> map =
    stream.collect(Collectors.toMap(s -> s, s -> 1, Integer::sum));

Upvotes: 2

Related Questions