Java lambda toMap 的 Map<String, Boolean>

K.N*_*las 1 java collections lambda

我不明白为什么会失败;

Map<String, Boolean> iMap = Arrays.asList("1","2","3","4","5").stream()
  .collect(Collectors.toMap(k->k, Boolean.TRUE));
Run Code Online (Sandbox Code Playgroud)

错误消息:

Multiple markers at this line
    - Type mismatch: cannot convert from T to K
    - The method toMap(Function<? super T,? extends K>, Function<? super T,? extends U>) 
      in the type Collectors is not applicable for the arguments ((<no type> k) -> {}, Boolean)
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏。

shm*_*sel 6

Collectors.toMap()Function两个参数均期望为 a 。你正在尝试传递 a Boolean。尝试这个:

Collectors.toMap(k->k, k->Boolean.TRUE)
Run Code Online (Sandbox Code Playgroud)