Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

You can convert all elements of a String array to ints and store them in an int array like this:

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 the parseIntArray(String[]) method in a map-reduce fashion in Java?

I heard that there is a simple way to do this with lambdas in Java 8. Was there also a map-reduce fashion way to do this prior to Java 8? I know this is 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 one page.

like image 701
Daniel S. Avatar asked Mar 16 '23 11:03

Daniel S.


1 Answers

One way to write it would be:

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

You could also start directly from the string:

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

private static int[] parseIntArray(String str) {
  return splitOnSpace.splitAsStream(str).mapToInt(Integer::parseInt).toArray();
}
like image 58
assylias Avatar answered Apr 15 '23 02:04

assylias