使用Java 8 Stream API将整数列表(List<Integer>)转换为映射表

9

我试图使用Java 8 stream 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 Stream API,正确的方法是什么?

1个回答

7

你正在传递一个布尔值映射器,应该传递一个 Function<Integer,Boolean>

正确的写法是:

Map<Integer, Boolean> m_map = m_list.stream().collect(
            Collectors.toMap(Function.identity(), e -> true));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接