Java splits string into Double []

I have this line:

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

I want to convert it to a Double []java array .

I tried:

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

Is there any more convenient and efficient way instead of converting a list array?

+4
source share
3 answers
Pattern pattern = Pattern.compile("-|\\.");

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

Also your drawing looks weird, it looks like it will be better [-,\\s]+

+13
source

Here's how you can do it using doublesinstead doubles.

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

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

Your input is a series of pairs of numbers, so here's how to get an array 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 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));
}
+1
source

Source: https://habr.com/ru/post/1691613/


All Articles