Java将字符串拆分为Double []

时间:2018-01-02 11:09:38

标签: java arrays list java-8

我有这个字符串:

((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();

有没有更好更有效的方法而不是数组列表数组转换?

3 个答案:

答案 0 :(得分:14)

Pattern pattern = Pattern.compile("-|\\.");

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

此外,您的模式看起来很奇怪,看起来这样会更合适[-,\\s]+

答案 1 :(得分:3)

以下是使用Doubles代替String string = "1 2 3 4"; Pattern pattern = Pattern.compile(" |,"); double[] results = pattern.splitAsStream(string) .mapToDouble(Double::parseDouble) .toArray(); 的方法。

SELECT o.order_id, o.firstname, o.lastname, os.name as status, o.date_added,o.shopper_id as shopper_id  , o.total, o.currency_code, o.currency_value FROM  `" . DB_PREFIX . "order` o LEFT JOIN " . DB_PREFIX . "order_status os ON (o.order_status_id = os.order_status_id) WHERE  o.store_id = '" . (int) $store_id . "' AND o.order_status_id = '" . (int) $status . "' AND os.language_id = '" . (int) $this->config->get('config_language_id') . "' AND ( o.shopper_id = NULL OR o.shopper_id = '0' )  ORDER BY o.order_id DESC

答案 2 :(得分:1)

您的输入数据似乎是一系列数字,所以这里是如何获得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));
}
相关问题