Java 8 Lambda String.Split映射错误

时间:2018-07-09 17:03:28

标签: java

我试图解析一个字符串列表,将它们按字符分割成一个映射,然后将输入解析为int。

基本上从“ 106S2”开始,我会得到一个整数{106,2}的地图。

问题在于:

  1. s.split(“ S”)[0]; //这里出现错误“无法解决拆分”
  2. 第二个lambda不会引发任何错误,但是如果我将其重写为s -> Integer.parseInt(s.split("S")[1])会再次给我一个错误。

我认为我没有做错任何事情,简写形式应该可以工作,但是在intellij和eclipse中,我都会出错。

    Map<String, Integer> c02 = Arrays.asList(
  "103S2", "106S2", "109S2", "112S2", "115S2", "118S2", "121S2", "124S2", "127S2", "130S2", "133S2", "136S2")
  .stream()
  .collect(
    Collectors.toMap(s -> {
      return s.split("S")[0]; // here i get error "cannot resolve split"
    }, s -> {
      String s1 = s.split("S")[1];
      return Integer.parseInt(s1);
    }));
System.out.println(c02);

2 个答案:

答案 0 :(得分:2)

结果应声明为Map<String, Integer>

所以它应该像这样:

Map<String, Integer> c02 = 
        Arrays.asList("103S2", "106S2", "109S2", "112S2", 
        "115S2", "118S2", "121S2", "124S2",
        "127S2", "130S2", "133S2", "136S2")
        .stream()
        .collect(Collectors.toMap(s -> s.split("S")[0], s -> {
            String s1 = s.split("S")[1];
            return Integer.valueOf(s1);
        }));

但是您的管道可以变得更简单(避免不必要的split调用):

Map<String, Integer> c02 = 
        Arrays.asList("103S2", "106S2", "109S2", "112S2", 
                "115S2", "118S2", "121S2", "124S2",
                "127S2", "130S2", "133S2", "136S2")
        .stream()
        .map(s -> s.split("S"))
        .collect(Collectors.toMap(s -> s[0], 
                s -> Integer.valueOf(s[1])));

答案 1 :(得分:0)

为了避免将来的代码重复,某些代码片段(例如s.split("S")[1]),我建议创建一个单独的实体来存储该对:

    class Pair {
        private final int k;
        private final int v;

        Pair(String raw) {
            this(raw.split("S"));
        }

        Pair(String[] raw) {
            this(raw[0], raw[1]);
        }

        Pair(String k, String v) {
            this(Integer.parseInt(k), Integer.parseInt(v));
        }

        Pair(int k, int v) {
            this.k = k;
            this.v = v;
        }

        public int getK() {
            return this.k;
        }

        public int getV() {
            return this.v;
        }
    }

这是一种更具功能性的方式,但更加清晰和易于维护。 最终的代码将如下所示。

    Map<Integer, Integer> collect = Stream.of(
            "103S2", "106S2", "109S2", "112S2", "115S2", "118S2", "121S2", "124S2", "127S2", "130S2", "133S2", "136S2")
            .map(Pair::new)
            .collect(Collectors.toMap(Pair::getK, Pair::getV));
    System.out.println(collect);

现在,您的代码更加清晰并完全解耦了。
另一个好处是,JIT将内联方法引用,并且运行速度更快。