Rea*_*son 1 java arrays java-stream collectors
我有这样的代码,它应该Map从整数数组创建一个。键代表位数。
public static Map<Integer, List<String>> groupByDigitNumbersArray(int[] x) {
return Arrays.stream(x) // array to stream
.filter(n -> n >= 0) // filter negative numbers
.collect(Collectors.groupingBy(n -> Integer.toString((Integer) n).length(), // group by number of digits
Collectors.mapping(d -> (d % 2 == 0 ? "e" : "o") + d,
Collectors.toList()))); // if even e odd o add to list
}
Run Code Online (Sandbox Code Playgroud)
问题与 一致mapping()。我收到错误:
public static Map<Integer, List<String>> groupByDigitNumbersArray(int[] x) {
return Arrays.stream(x) // array to stream
.filter(n -> n >= 0) // filter negative numbers
.collect(Collectors.groupingBy(n -> Integer.toString((Integer) n).length(), // group by number of digits
Collectors.mapping(d -> (d % 2 == 0 ? "e" : "o") + d,
Collectors.toList()))); // if even e odd o add to list
}
Run Code Online (Sandbox Code Playgroud)
有人知道如何解决这个问题吗?
原始的 Streamscollect()无法提供需要 aCollector作为参数的风格。即使没有模数运算符,您的代码也不会编译 - 注释掉下游收集器以查看我在说什么。%groupingBy()
您需要应用boxed()操作才能将 an 转换IntStream为对象流Stream<Integer>。
您的方法可能如下所示:
public static Map<Integer, List<String>> groupByDigitNumbersArray(int[] x) {
return Arrays.stream(x) // creates a stream over the given array
.filter(n -> n >= 0) // retain positive numbers and zero
.boxed() // <- converting IntStream into a Stream<Integer>
.collect(Collectors.groupingBy(
n -> String.valueOf(n).length(), // group by number of digits
Collectors.mapping(d -> (d % 2 == 0 ? "e" : "o") + d, // if even concatinate 'e', if odd 'o'
Collectors.toList()))); // collect to list
}
Run Code Online (Sandbox Code Playgroud)
我已经更改了classifier函数groupingBy()以使其更具可读性。