Unk*_*own 6 collections arraylist hashmap java-8 java-stream
我想一个简单的转换List<Integer>为Map使用Java 8个流API,并得到了以下编译时错误:
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)
Run Code Online (Sandbox Code Playgroud)
我的代码:
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));
Run Code Online (Sandbox Code Playgroud)
我也尝试了下面的第二种方法,但得到了同样的错误.
Map<Integer, Boolean> m_map = m_list.stream().collect(
Collectors.toMap(Integer::intValue, true));
Run Code Online (Sandbox Code Playgroud)
使用Java 8流API执行此操作的正确方法是什么?
您正在传递boolean值映射器.你应该通过一个Function<Integer,Boolean>.
它应该是:
Map<Integer, Boolean> m_map = m_list.stream().collect(
Collectors.toMap(Function.identity(), e -> true));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
885 次 |
| 最近记录: |