在我的示例中,我尝试从一系列字符创建一个 ASCII 表。我设法用一个List字符串来做,但用一个字符数组失败了。
我收到Character::hashCode无法在Collectors.toMap().
Error:(26, 17) java: 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.Object>>
reason: cannot infer type-variable(s) R
(actual and formal argument lists differ in length)
Error:(26, 42) java: incompatible types: cannot infer type-variable(s) T,K,U,T
(argument mismatch; invalid method reference
incompatible types: java.lang.Object cannot be converted to char)
有办法吗?
public class JavaCollectToMapEx2 {
public static void main(String[] args) {
// list of ASCII characters
var chars = List.of("a", "b", "c", "d", "e", "f",
"g", "h", "i", "j", "k", "l", "m", "n",
"o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z");
// CharSequence chars2 = "abcdefghijklmnopqrstuvwxyz";
char[] letters = "abcdefghijklmnopqrstuvwxyz".toCharArray();
// Map to represent ASCII character table
Map<Integer, String> asciiMap = chars.stream()
.collect(Collectors.toMap(String::hashCode, Function.identity()));
Map<Integer, Character> asciiMap2 = CharBuffer.wrap(letters).chars()
.collect(Collectors.toMap(Character::hashCode, Function.identity()));
System.out.println(asciiMap);
System.out.println(asciiMap2);
}
}
Smart猫小萌
慕码人2483693
有只小跳蛙
相关分类