将Map <integer,string =“”>转换为Map <string,string =“”>

时间:2019-04-15 02:33:01

标签: java java-8 java-stream

我想将Map转换为Map

到目前为止,我在下面尝试过

Map<Integer, String> inMap = new HashMap();
        inMap.put(100, "Test1");
        inMap.put(101, "Test2");
        inMap.put(102, "Test3");
  

如何在Entry :: getKey上应用String.valueOf()?

    Map<String, String> collect = inMap.entrySet().stream().collect(Collectors.toMap(Entry::getKey, Entry::getValue));  //how to apply String.valueOf() on Entry::getKey
  

这正在工作

    Map<String, String> map1 = inMap.entrySet().stream().collect(Collectors.toMap(entry -> String.valueOf(entry.getKey()), Map.Entry::getValue, (a, b) -> b)); //Working
  

为什么String.valueOf(entry.getKey()),entry.getValue()即使其双重功能也不起作用?

    Map<String, String> map2 = inMap.entrySet().stream().collect(Collectors.toMap(entry -> String.valueOf(entry.getKey()), entry.getValue()));  //

2 个答案:

答案 0 :(得分:3)

因为entry.getValue()不是Function,而是entry -> entry.getValue()

Map<String, String> map = inMap.entrySet()
                               .stream()
                               .collect(Collectors.toMap(entry -> String.valueOf(entry.getKey()), entry -> entry.getValue()); // should work

或者您可以简单地将forEach用作:

Map<String, String> outMap = new HashMap<>();
inMap.forEach((k, v) -> outMap.put(k.toString(), v));

答案 1 :(得分:3)

您还可以使用toString(),因为在所有包装器类中,toString()被覆盖以返回值

 Map<String, String> collect = inMap.entrySet()
                                    .stream()
                                    .collect(Collectors.toMap(entry->entry.getKey().toString(), Entry::getValue));