无法解析Java流中的方法Character :: hashCode

Jan*_*nar 3 java lambda java-8 java-stream

在我的示例中,我尝试根据一系列字符创建一个ASCII表。我设法用a List字符串完成了操作,但是用了一个char数组失败了。

我收到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)
Run Code Online (Sandbox Code Playgroud)

有办法吗?

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

nic*_*ckb 6

.chars()给您一个IntStream,它是原始流int,而不是字符流(更多信息)。这就是为什么没有方法引用Character起作用的原因。

要实现您想要的目标,您Stream<Character>首先需要:

Map<Integer, Character> asciiMap2 = CharBuffer.wrap(letters)
        .chars()
        .mapToObj(e -> (char) e)
        .collect(Collectors.toMap(e -> e.hashCode(), Function.identity()));
Run Code Online (Sandbox Code Playgroud)

现在,仍然存在使用方法引用获取哈希码的问题。您无法使用,Character::hashCode因为它对所需的方法不明确,因为有两种可能:

  1. 覆盖Object#hashCode,
  2. 静态方法 int hashCode(char value)

您可以从这段代码中看到,两者都满足的第一个参数toMap():

Function<Character, Integer> f1 = e -> Character.hashCode(e);
Function<Character, Integer> f2 = e -> e.hashCode();
Run Code Online (Sandbox Code Playgroud)

若要解决此问题,可以将其Object::hashCode用于非静态方法调用。