Java 8 Convert a simple List to Map

∥☆過路亽.° 提交于 2020-01-21 18:58:08

问题


import java.util.function.*;
import java.util.*;
public class Main
{
    public static void main(String[] args) {
        List<Integer> newList = new ArrayList<Integer>();
        newList.add(1);
        newList.add(2);
        newList.add(3);
        newList.add(4);

        Map<Integer,String> formMap = new LinkedHashMap<Integer,String>(); 
        Function<Integer,Map<Integer,String>> myFunc = i->{
          if(i%2==0)
          {
              formMap.put(i,"even");
          }
          return formMap;
        };

        Map<Integer,String> newMap = newList.stream().map(i->myFunc.apply(i)).collect(Collectors.toMap(
        entry -> entry.getKey(), // keyMapper
        entry -> entry.getValue(), // valueMapper
        (first, second) -> first,  // mergeFunction
        () -> new LinkedHashMap<>() // mapFactory
    ));

    }
}

How to convert a simple list as above into a map by performing some operations on the objects on list and then putting it in map. I took the above Collectors.toMap() code from the net only. Please help me with the above query/code .


回答1:


Your map step converts a Stream<Integer> to a Stream<Map<Integer,String>>. In order to collect that Stream to a single Map, you can write:

Map<Integer,String> newMap = 
    newList.stream()
           .flatMap(i->myFunc.apply(i).entrySet().stream())
           .collect(Collectors.toMap(Map.Entry::getKey, // keyMapper
                                     Map.Entry::getValue, // valueMapper
                                     (first, second) -> first,  // mergeFunction
                                     LinkedHashMap::new)); // mapFactory

or

Map<Integer,String> newMap = 
    newList.stream()
           .map(myFunc)
           .flatMap(m->m.entrySet().stream())
           .collect(Collectors.toMap(Map.Entry::getKey, // keyMapper
                                     Map.Entry::getValue, // valueMapper
                                     (first, second) -> first,  // mergeFunction
                                     LinkedHashMap::new)); // mapFactory

Of course, if all you want is to filter out the odd numbers and map the remaining numbers to "even", you can simply write:

Map<Integer,String> newMap = 
    newList.stream()
           .filter(i -> i % 2 == 0)
           .collect(Collectors.toMap(Function.identity(),
                                     i -> "even",
                                     (first, second) -> first,
                                     LinkedHashMap::new));


来源:https://stackoverflow.com/questions/59714677/java-8-convert-a-simple-list-to-map

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!