9

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 Answer 1

8

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.