vlad
vlad

Reputation: 41

How to convert a List of strings into a Map with Streams

I have to convert a list List<String> into a map Map<String, Float>.

The keys of the map must be strings from the list, and every value must be 0 (zero) for all keys.

How can I convert this?

I've tried:

List<String> list = List.of("banana", "apple", "tree", "car");

Map<String, Float> map = list.stream()
    .distinct()
    .collect(Collectors.toMap(String::toString, 0f));

Upvotes: 2

Views: 1525

Answers (3)

prost&#253; člověk
prost&#253; člověk

Reputation: 939

The below works fine,


Map<String, Float> collect =  
 list.stream() .collect(Collectors
     .toMap(Function.identity(),
             a -> 0f));

Upvotes: 1

Sayan Bhattacharya
Sayan Bhattacharya

Reputation: 1368

Another way doing the the same without using stream.

Map<String,Float> map = new HashMap<String, Float>();       
list.forEach(s-> map.computeIfAbsent(s,v->0f));

Upvotes: 2

Alexander Ivanchenko
Alexander Ivanchenko

Reputation: 29058

If you need to associate every key with 0, the second argument of the toMap() needs to be a function returning 0, but not the value of 0:

Map<String, Float> map = list.stream()
    .collect(Collectors.toMap(
        Function.identity(),  // extracting a key
        str -> 0f,            // extracting a value
        (left, right) -> 0f   // resolving duplicates
    ));

Also, there's no need to use distinct(). Under the hood, it'll create a LinkedHashSet to eliminate duplicates, in case if most of the stream elements are unique and the data set is massive, it might significantly increase memory consumption.

Instead, we can deal with them within the map. For that we need to add the third argument mergeFunction.

And there's no need to invoke toString() method on a stream element which is already a string to extract a key of type String. In such cases, we can use Function.identity() to signify that no transformations required.

Upvotes: 3

Related Questions