【问题标题】:Java split string to Double[ ]Java 将字符串拆分为 Double[ ]
【发布时间】:2018-01-02 11:09:37
【问题描述】:

我有这个字符串:

((39.4189453125 37.418708616699824,42.0556640625 37.418708616699824,43.4619140625 34.79181436843146,38.84765625 33.84817790215085,39.4189453125 37.418708616699824))

我想将其转换为Double [] java 数组。

我试过了:

String[]tokens = myString.split(" |,");
Arrays.asList(tokens).stream().map(item -> Double.parseDouble(item)).collect(Collectors.toList()).toArray();

有没有比数组-列表-数组转换更好更高效的方法?

【问题讨论】:

  • 您不需要将它们收集到一个列表中。您可以使用 toArray(Double[]::new) 从流直接转到数组
  • 另外,如果您需要Doubles 而不是doubles,您可以使用Double.valueOf 而不是Double.parseDouble
  • 避免使用Double,它会浪费大量内存并且速度会慢很多。
  • @khelwood 我可以把它加倍吗?
  • @EladBenda2 是的,如果您使用mapToDouble(Double::parseDouble),您将获得DoubleStream

标签: java arrays list java-8


【解决方案1】:
Pattern pattern = Pattern.compile("-|\\.");

pattern.splitAsStream(test) // your String
       .map(Double::parseDouble)
       .toArray(Double[]::new);

而且你的模式看起来很奇怪,看起来这更适合[-,\\s]+

【讨论】:

  • @BoristheSpider 我更喜欢 java-9 中的Scanner.findAll
  • Double::valueOf 会不会比 Double.parseDouble 更可取(它返回需要自动装箱的 double)?
  • @khelwood meh - 在这里装箱或在那里装箱;差别不大。
  • 根据给定的模式和 OP 的示例输入,我仍然不相信这个答案会起作用。
  • @KlitosKyriacou 是的,模式最奇怪。
【解决方案2】:

以下是使用doubles 而不是Doubles 的方法。

String string = "1 2 3 4";
Pattern pattern = Pattern.compile(" |,");

double[] results = pattern.splitAsStream(string)
                          .mapToDouble(Double::parseDouble)
                          .toArray();

【讨论】:

    【解决方案3】:

    您的输入数据似乎是一系列数字对,因此这里是获取double[][2] 数组的方法。

    public static void main(String[] args) {
        final String data = "(("
                + "39.4189453125 37.418708616699824,"
                + "42.0556640625 37.418708616699824,"
                + "43.4619140625 34.79181436843146,"
                + "38.84765625   33.84817790215085,"
                + "39.4189453125 37.418708616699824"
                + "))";
    
        final Pattern topLevelPattern = Pattern.compile("\\(\\((.*)\\)\\)");
        final Pattern pairSeparator = Pattern.compile(",");
    
        Matcher topLevelMatcher = topLevelPattern.matcher(data);
        if (!topLevelMatcher.matches())
            throw new IllegalArgumentException("Data not surrounded by double parentheses");
    
        String topLevelData = topLevelMatcher.group(1);  // whatever's inside the parentheses
    
        double[][] pairsArray = pairSeparator.splitAsStream(topLevelData)
                .map(s -> s.split("\\s+"))  // array[2] of strings representing doubles
                .map(a -> new double[]{Double.parseDouble(a[0]), Double.parseDouble(a[1])})
                .toArray(double[][]::new);
    
        for (double[] pair : pairsArray)
            System.out.println(Arrays.toString(pair));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-31
      相关资源
      最近更新 更多