javadictionaryjava-stream

How to create a map with key and value equals 0


I have list of long named list1.
I need to create a Map<Long, Long> (using the 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.


Solution

  • If you need to preserve the order, use LinkedHashMap:

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

    otherwise it is simpler:

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

    if no duplicated values expected, then even more simpler:

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

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

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