【问题标题】:Collect list of Integer (List<Integer>) to map with Java 8 Stream API收集整数列表 (List<Integer>) 以映射到 Java 8 Stream API
【发布时间】:2019-04-19 08:38:21
【问题描述】:

我尝试使用 Java 8 流 API 将简单的 List&lt;Integer&gt; 转换为 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


    【解决方案1】:

    您正在为值映射器传递boolean。你应该传递一个Function&lt;Integer,Boolean&gt;

    应该是:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-06
      • 2017-09-26
      相关资源
      最近更新 更多