简体   繁体   中英

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

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.

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

The below works fine,


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM