7

I have the below code and would like to use java 8 to convert a list of Long to a 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 I try to map the individual value in the list as the key of the map.

Eran
  • 387,369
  • 54
  • 702
  • 768
Erica
  • 97
  • 2
  • 4

2 Answers2

8

The second argument of toMap is also a Function, so you can't just pass globalVal.

Map<Long, Long> map = queryLongs.stream()
                                .collect(Collectors.toMap(Function.identity(), 
                                                          i->globalVal));
Eran
  • 387,369
  • 54
  • 702
  • 768
  • 1
    I get the issue saying that my variable globalVal shoud be final or effectivefinal. Is there a way to overcome this? – Erica Oct 26 '17 at 12:16
  • 1
    @Erica Are you changing its value anywhere? If you are, it can't be used in a lambda expression. If you are not, it is effectively final, and everything should be fine. – Eran Oct 26 '17 at 12:18
  • 2
    @Erica, just copy it in a temporary `final` variable and use that one in the lambda – Didier L Oct 26 '17 at 12:20
  • Thanks for the feedback @Didier. Keeping a copy of the variable into a final one helped. – Erica Oct 26 '17 at 12:26
  • Thanks for the solution @Eran – Erica Oct 26 '17 at 12:26
1

Here's a way without using streams (still using Java 8 features, though):

Map<Long, Long> map = new HashMap<>();
queryLongs.forEach(i -> map.put(i, globalVal));
fps
  • 33,623
  • 8
  • 55
  • 110