Java List< String>映射到< String,Integer>转换 [英] Java List<String> to Map<String, Integer> convertion
问题描述
我想从java 8中的List<String>
转换为Map <String, Integer>
,如下所示:
I'd like to convert a Map <String, Integer>
from List<String>
in java 8 something like this:
Map<String, Integer> namesMap = names.stream().collect(Collectors.toMap(name -> name, 0));
因为我有一个字符串列表,所以我想创建一个Map,键是列表的字符串,值是Integer(零).
because I have a list of Strings, and I'd like to to create a Map, where the key is the string of the list, and the value is Integer (a zero).
我的目标是计算字符串列表的元素(在我的代码中后来出现).
My goal is, to counting the elements of String list (later in my code).
我知道以旧"方式进行转换很容易;
I know it is easy to convert it, in the "old" way;
Map<String,Integer> namesMap = new HasMap<>();
for(String str: names) {
map1.put(str, 0);
}
但是我想知道是否还有Java 8解决方案.
but I'm wondering there is a Java 8 solution as well.
推荐答案
As already noted, the parameters to Collectors.toMap
have to be functions, so you have to change 0
to name -> 0
(you can use any other parameter name instead of name
).
但是,请注意,如果names
中存在重复项,此操作将失败,因为这将导致结果映射中的键重复.要解决此问题,您可以通过
Note, however, that this will fail if there are duplicates in names
, as that will result in duplicate keys in the resulting map. To fix this, you could pipe the stream through Stream.distinct
first:
Map<String, Integer> namesMap = names.stream().distinct()
.collect(Collectors.toMap(s -> s, s -> 0));
或者根本不初始化这些默认值,而使用 computeIfAbsent
代替:
Or don't initialize those defaults at all, and use getOrDefault
or computeIfAbsent
instead:
int x = namesMap.getOrDefault(someName, 0);
int y = namesMap.computeIfAbsent(someName, s -> 0);
或者,如果要获取名称的计数,则可以使用 Collectors.counting
:
Or, if you want to get the counts of the names, you can just use Collectors.groupingBy
and Collectors.counting
:
Map<String, Long> counts = names.stream().collect(
Collectors.groupingBy(s -> s, Collectors.counting()));
这篇关于Java List< String>映射到< String,Integer>转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!