【发布时间】:2019-04-19 08:38:21
【问题描述】:
我尝试使用 Java 8 流 API 将简单的 List<Integer> 转换为 Map 并得到以下编译时错误:
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)
我的代码:
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));
我也尝试了下面的第二种方法,但得到了同样的错误。
Map<Integer, Boolean> m_map = m_list.stream().collect(
Collectors.toMap(Integer::intValue, true));
使用 Java 8 流 API 执行此操作的正确方法是什么?
【问题讨论】:
标签: arraylist collections java-8 hashmap java-stream