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?
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With