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
}
ラビンドラRanwala:

あなたは使用することができ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) + "")); 

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=178241&siteId=1