Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collect list of Integer (List<Integer>) to map with Java 8 Stream API

I tried to convert a simple List<Integer> to a Map using Java 8 stream API and got the following compile time error:

The method toMap(Function<? super T,? extends K>, Function<? super T,? 
extends U>) in the type Collectors is not applicable for the arguments 
(Function<Object,Object>, boolean)

My code:

ArrayList<Integer> m_list = new ArrayList<Integer>();

m_list.add(1);
m_list.add(2);
m_list.add(3);
m_list.add(4);

Map<Integer, Boolean> m_map = m_list.stream().collect(
                Collectors.toMap(Function.identity(), true));

I also tried the second method below but got the same error.

Map<Integer, Boolean> m_map = m_list.stream().collect(
                Collectors.toMap(Integer::intValue, true));

What is the correct way to do this using Java 8 stream API?

like image 702
Unknown Avatar asked Nov 16 '18 07:11

Unknown


People also ask

Can we cast List to map in Java?

With Java 8, you can convert a List to Map in one line using the stream() and Collectors. toMap() utility methods. The Collectors. toMap() method collects a stream as a Map and uses its arguments to decide what key/value to use.


1 Answers

You are passing a boolean for the value mapper. You should pass a Function<Integer,Boolean>.

It should be:

Map<Integer, Boolean> m_map = m_list.stream().collect(
            Collectors.toMap(Function.identity(), e -> true));
like image 156
Eran Avatar answered Sep 18 '22 10:09

Eran