在Java 8中将字符串转换为Map <Integer,String>

Rah*_*pta 5 java hashmap java-8

有人可以指导我如何使用Java 8实现以下目标吗?我不知道如何将计数器作为关键

String str = "abcd";

Map<Integer,String> map = new HashMap<>();

String[] strings = str.split("");

int count =0;
for(String s:strings){
    map.put(count++, s);// I want the counter as the key
}
Run Code Online (Sandbox Code Playgroud)

Rav*_*ala 5

您可以IntStream用来完成此任务。使用整数值作为键,并使用该索引处字符串数组中的相关值作为映射值。

Map<Integer, String> counterToStr = IntStream.range(0, strings.length)
    .boxed()
    .collect(Collectors.toMap(Function.identity(), i -> strings[i]));
Run Code Online (Sandbox Code Playgroud)

消除需求的另一种选择split是,

Map<Integer, String> counterToStr = IntStream.range(0, strings.length)
    .boxed()
    .collect(Collectors.toMap(Function.identity(), i -> str.charAt(i) + "")); 
Run Code Online (Sandbox Code Playgroud)