Mapreduce way to convert all String [] to int [] elements in Java?

You can convert all elements of the array Stringto intand store them in the array intas follows:

public static final void main(String[] args) {
    String input = "1 2 5 17 23 12 5 72 123 74 13 19 32";
    String[] strAr = input.split(" ");

    int[] output = parseIntArray(strAr);
}

private static int[] parseIntArray(String[] strAr) {
    // convert to int[] one by one
    int[] output = new int[strAr.length];
    for (int i = 0; i < strAr.length; i++) {
        output[i] = Integer.parseInt(strAr[i]);
    }

    return output;
}

How can you write a method parseIntArray(String[])in a map reduction method in Java?

I heard that there is an easy way to do this using lambdas in Java 8. Was there also a way to reduce the map size for this to Java 8? I know that these are two questions in one; however, I believe that they are so closely related that it is better for the community to have both of these answers on the same page.

+4
source share
3 answers

One way to record:

private static int[] parseIntArray(String[] strAr) {
  return Stream.of(strAr).mapToInt(Integer::parseInt).toArray();
}

:

private static final Pattern splitOnSpace = Pattern.compile(" ");

private static int[] parseIntArray(String str) {
  return splitOnSpace.splitAsStream(str).mapToInt(Integer::parseInt).toArray();
}
+6

lambdas Java 8

private static int[] parseIntArray(String input) {

    return Arrays.asList(input.split(" "))
            .stream()
            .flatMapToInt(n-> IntStream.of(Integer.parseInt(n)) )
            .toArray();
}

for, , .

Java 8 - rxJava .

+1

Another simple suggestion:

String input = "1 2 5 17 23 12 5 72 123 74 13 19 32";
int[] numbers = Stream.of(input.split(" ")).mapToInt(Integer::parseInt).toArray();
0
source

All Articles