有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

要映射的java数组:找不到适合收集器的方法。托马普

我想使用Java 8流将数组转换为映射:

String[] arr = {"two", "times", "two", "is", "four"};
Arrays.stream(arr).collect(Collectors.toMap(s -> s, 1, Integer::sum);

s -> s部分被标记为错误

no instance(s) of type variable(s) T, U exists so that Integer conforms to Function


共 (1) 个答案

  1. # 1 楼答案

    实际上1就是错误。值1不能用作valueMapper,其类型应为Function<? super T, ? extends U>

    在您的示例中,值映射器应该是一个函数,它接受Stream(a String)的元素并返回Integer。lambda表达式s -> 1就可以了

    以下工作:

    String[] arr = {"two", "times", "two", "is", "four"};
    Map<String,Integer> map = Arrays.stream(arr).collect(Collectors.toMap(s -> s, s -> 1, Integer::sum));
    System.out.println (map);
    

    输出:

    {times=1, four=1, is=1, two=2}