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

Viewed 5411

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?

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));
Related