簡體   English   中英

如何創建一個鍵值為 0 的 map

[英]How to create a map with key and value equals 0

我有一個名為list1long列表。
我需要創建一個Map<Long, Long> (使用 stream api),其中key是來自list1value ,這個 key = 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));

或者只使用傳統的循環(同意 Thomas 的觀點,這樣更容易理解):

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM