Home > OS >  How to convert a List of strings into a Map with Streams
How to convert a List of strings into a Map with Streams

Time:06-25

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

CodePudding user response:

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.

CodePudding user response:

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