Java 8将简单的列表转换为Map [英] Java 8 Convert a simple List to Map

查看:102
本文介绍了Java 8将简单的列表转换为Map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

    }
}

如何通过对列表上的对象执行一些操作,然后将其放入地图中,将上述简单列表转换为地图. 我仅从网上获取了上面的Collectors.toMap()代码. 请帮我解决上面的查询/代码.

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 .

推荐答案

您的map步骤将Stream<Integer>转换为Stream<Map<Integer,String>>.为了将Stream收集到单个Map中,您可以编写:

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

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

这篇关于Java 8将简单的列表转换为Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆