代码之家  ›  专栏  ›  技术社区  ›  Rahul Gupta

在Java 8中将字符串转换为“整数”、“字符串”>

  •  1
  • Rahul Gupta  · 技术社区  · 6 年前

    有人可以指导我如何使用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
    }
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Ravindra Ranwala    6 年前

    你可以使用 IntStream 完成这件事。使用整数值作为键,使用该索引处字符串数组中的相关值作为映射的值。

    Map<Integer, String> counterToStr = IntStream.range(0, strings.length)
        .boxed()
        .collect(Collectors.toMap(Function.identity(), i -> strings[i]));
    
        2
  •  0
  •   Vishwa Ratna    6 年前
    String str = "abcd";
    
            Map<Integer,String> map = new HashMap<>();
    
            String[] strings = str.split("");
    
            for(int i=0;i<strings.length;i++)
            {
                map.put(i, strings[i]);
            }
            map.forEach((k,v)->System.out.println(k+" "+v));