我有名为
long
的 list1
列表。Map<Long, Long>
(使用流 api),其中 key
是来自 value
的 list1
,并且该键的值 = 0
;list1 = [1, 2, 3, 1, 3]
map = [ [1,0], [2,0], [3,0] ]
在这种情况下顺序并不重要
如果您需要保留订单,请使用
LinkedHashMap
:
Map<Long, Long> map =
list1.stream().collect(Collectors.toMap(x->x, x->0L, (x, y)->x, LinkedHashMap<Long, Long>::new));
否则更简单:
Map<Long, Long> result = list1.stream().collect(Collectors.toMap(x->x, x->0L, (x, y)->x));
如果不需要重复值,则更简单:
Map<Long, Long> result = list1.stream().collect(Collectors.toMap(x->x, x->0L));
或者只是使用传统的循环(同意托马斯的观点,这样更容易理解):
Map<Long, Long> map = new LinkedHashMap<>();
for (Long x: list1) {
map.put(x, 0L);
}
使用简单的 foreach 来替代流:
List<Long> list = List.of(1L, 2L, 3L, 1L, 3L);
Map<Long,Long> map = new HashMap<>();
list.forEach(i -> map.computeIfAbsent(i, v -> 0L));
System.out.println(map);
我认为 JDK 没有提供相当于
Function.identity()
的功能,而不是返回函数参数,而是返回一个常量值,这是一个遗憾。因此,如果您发现自己在项目中一遍又一遍地初始化具有常量或默认值的地图,我建议使用以下方法定义一个实用程序类(直接受到 Function.identity()
源的启发)代码):
public final class Functions {
public static <T, R> Function<T, R> value(R r) {
return t -> r;
}
}
并按以下方式使用它:
Map<Long, Long> map = list.stream()
.collect(Collectors.toMap(
Function.identity(),
Functions.value(0L)
));