将foreach改为lambda表达式

时间:2017-11-03 14:52:43

标签: java lambda foreach java-8

我想将foreach改为lambda表达式。我做对了吗?

Map<String, String> countriesToChooseAsMainCountry = new LinkedHashMap<String, String>();

FOREACH:

for (Country country : project.getCountries()) {
   countriesToChooseAsMainCountry.put(Long.toString(country.getId()), country.getName());
}

LAMBDA:

project.getCountries()
       .forEach(country -> countriesToChooseAsMainCountry.put(Long.toString(country.getId()), country.getName()));

如果我说得对,我能以某种方式改善这种可读性吗?感谢。

1 个答案:

答案 0 :(得分:3)

您可以将Collectors.toMap用作:

project.getCountries()
       .stream()
       .collect(Collectors.toMap(country -> Long.toString(country.getId()), // key
                                 Country::getName, //value 
                                 (a, b) -> b, // function to determine the value in case of same country ids (which is essentially overriding the value) 
                                 LinkedHashMap::new));

它会阻止你进入forEach的不确定行为,虽然你当前的实现(要求)似乎没问题。