Home > Back-end >  How to create a map with key and value equals 0
How to create a map with key and value equals 0

Time:10-11

I have list of long named list1.
I need to create a Map<Long, Long> (using stream api), where key is value from list1 and value for this key = 0;
e.g

list1 = [1, 2, 3, 1, 3]
map = [ [1,0], [2,0], [3,0] ] 

The order doesn't matter in this case

CodePudding user response:

An alternative to streams using a simple 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);

CodePudding user response:

If you need to preserve the order, use LinkedHashMap:

Map<Long, Long> map = 
     list1.stream().collect(Collectors.toMap(x->x, v->0L, (x, y)->x, LinkedHashMap<Long, Long>::new));

otherwise it is simpler:

Map<Long, Long> result = list1.stream().collect(Collectors.toMap(x->x, v->0L, (x, y)->x));

if no duplicated values expected, then even more simpler:

Map<Long, Long> result = list1.stream().collect(Collectors.toMap(x->x, v->0L));

or just use a traditional loop (agree with Thomas, it is easier to understand):

Map<Long, Long> map = new LinkedHashMap<>();
for (Long key : list1) {
    map.put(key, 0L);
}
  • Related