Java 属性和 lambda 收集

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23887691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 08:52:27  来源:igfitidea点击:

Java Properties and lambda collect

javalambdajava-8

提问by Andrea Catania

I have a method that convert Properties into hashmap in this way (i know it's wrong)

我有一个以这种方式将属性转换为哈希图的方法(我知道这是错误的)

Map<String, String> mapProp = new HashMap<String, String>();
Properties prop = new Properties();
prop.load(new FileInputStream( path ));     

prop.forEach( (key, value) -> {mapProp.put( (String)key, (String)value );} );

return mapProp;

My idea is that mapping in a way like this:

我的想法是以这样的方式映射:

Properties prop = new Properties();
prop.load(new FileInputStream( path ));

Map<String, String> mapProp = prop.entrySet().stream().collect( /*I don't know*/ );

return mapProp;

How write a lambda expression for do that?

如何为此编写 lambda 表达式?

Thanks all in advance

提前谢谢大家

Andrea.

安德烈亚。

采纳答案by Lukasz Wiktor

Use Collectors.toMap

使用Collectors.toMap

Properties prop = new Properties();
prop.load(new FileInputStream( path ));

Map<String, String> mapProp = prop.entrySet().stream().collect(
    Collectors.toMap(
        e -> (String) e.getKey(),
        e -> (String) e.getValue()
    ));

回答by OldCurmudgeon

Not actually an answer but may be useful to know for others passing by.

实际上不是答案,但可能对路过的其他人有用。

Since Propertiesextends Hashtable<Object,Object>which implements Map<K,V>you should not need to do anything other than:

由于Propertiesextends Hashtable<Object,Object>which 实现,Map<K,V>你不需要做任何事情,除了:

    Properties p = new Properties();
    Map<String,String> m = new HashMap(p);

Not quite sure why no warnings are offered for this code as it implies a cast from Map<Object,Object>to Map<String,String>is acceptable but I suspect that is a separate question.

不太确定为什么没有为此代码提供警告,因为它意味着从Map<Object,Object>to的强制转换Map<String,String>是可以接受的,但我怀疑这是一个单独的问题。

回答by niraj.nijju

for those who want to use forEach

对于那些想要使用 forEach 的人

HashMap<String, String> propMap = new HashMap<>();
prop.forEach((key, value)-> {
   propMap.put( (String)key, (String)value);
});