How to convert <Long> list to <Long, Long> map

I have the code below and would like to use java 8 to convert a list Longto Map<Long,Long>.

Long globalVal= 10;
List<Long> queryLongs = Arrays.asList(600L,700L,800L);
Map<Long, Long> map = queryLongs.stream().collect(Collectors.toMap(i->i, globalVal)));

I get an error when trying to match an individual value in the list as a card key.

+4
source share
2 answers

The second argument is toMapalso Function, so you cannot just pass globalVal.

Map<Long, Long> map = queryLongs.stream()
                                .collect(Collectors.toMap(Function.identity(), 
                                                          i->globalVal));
+8
source

Here you can use a non-threading method (still using Java 8 features):

Map<Long, Long> map = new HashMap<>();
queryLongs.forEach(i -> map.put(i, globalVal));
+1
source

Source: https://habr.com/ru/post/1688209/


All Articles