有人可以指导我如何使用 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
}
您可以使用IntStream
为了完成这件事。使用整数值作为键,并将字符串数组中该索引处的相关值作为映射的值。
Map<Integer, String> counterToStr = IntStream.range(0, strings.length)
.boxed()
.collect(Collectors.toMap(Function.identity(), i -> strings[i]));
另一种替代方案可以消除需要split
将会,
Map<Integer, String> counterToStr = IntStream.range(0, strings.length)
.boxed()
.collect(Collectors.toMap(Function.identity(), i -> str.charAt(i) + ""));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)