此代码可以与其他对象配合使用,但不能与 int 配合使用,即使这些对象会自动装箱为 Integer。我无法理解错误消息。
jshell> String[] names = new String[]{"apple", "apple", "banana"};
names ==> String[3] { "apple", "apple", "banana" }
jshell> Map<String, Integer> stringMap = Arrays.stream(names).collect(Collectors.groupingBy(Function.identity(), Collectors.summingInt(e -> 1)));
stringMap ==> {banana=1, apple=2}
jshell> int[] nums = new int[]{1,2,3,3,4};
nums ==> int[5] { 1, 2, 3, 3, 4 }
jshell> Map<Integer, Integer> numsMap = Arrays.stream(nums).collect(Collectors.groupingBy(Function.identity(), Collectors.summingInt(e -> 1)));
| Error:
| method collect in interface java.util.stream.IntStream cannot be applied to given types;
| required: java.util.function.Supplier<R>,java.util.function.ObjIntConsumer<R>,java.util.function.BiConsumer<R,R>
| found: java.util.stream.Collector<java.lang.Object,capture#1 of ?,java.util.Map<java.lang.Object,java.lang.Integer>>
| reason: cannot infer type-variable(s) R
| (actual and formal argument lists differ in length)
| Map<Integer, Integer> numsMap = Arrays.stream(nums).collect(Collectors.groupingBy(Function.identity(), Collectors.summingInt(e -> 1)));
| ^-------------------------^
正如 Pshemo 所评论的,
IntStream
不是 auto-box。您仅在 int
中使用 IntStream
原语。
IntStream#boxed
的调用,您的代码就可以工作。
// Integer
int[] ints = new int[] { 1 , 2 , 3 , 3 , 4 };
Map < Integer, Integer > integersMap =
Arrays
.stream ( ints )
.boxed ()
.collect (
Collectors.groupingBy (
Function.identity ( ) ,
Collectors.summingInt ( e -> 1 )
)
);
System.out.println ( "integersMap = " + integersMap );
stringMap = {香蕉=1,苹果=2}
并且,作为参考,
String
代码。
// String
String[] names = new String[] { "apple" , "apple" , "banana" };
Map < String, Integer > stringMap =
Arrays
.stream ( names )
.collect (
Collectors.groupingBy (
Function.identity ( ) ,
Collectors.summingInt ( e -> 1 )
)
);
System.out.println ( "stringMap = " + stringMap );
整数映射 = {1=1, 2=1, 3=2, 4=1}