Created
April 15, 2020 03:52
-
-
Save sureshsarda/565550fbed856661a6c4a90ac817a2dd to your computer and use it in GitHub Desktop.
Convert String to Integer and 2D Integer Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class StringTo2DArray implements Function<String, int[][]> { | |
@Override | |
public int[][] apply(String s) { | |
String trimmed = s.trim(); | |
String arraysString = s.substring(1, trimmed.length() - 1); | |
String[] arrays = arraysString.replaceAll("]\\s*,\\s*\\[", "]\n[") | |
.split("\n"); | |
StringToArray mapper = new StringToArray(); | |
return Arrays.stream(arrays) | |
.map(mapper) | |
.toArray(int[][]::new); | |
} | |
} | |
public static class StringToArray implements Function<String, int[]> { | |
@Override | |
public int[] apply(String s) { | |
String trimmed = s.trim(); | |
return Arrays.stream(trimmed.substring(1, trimmed.length() - 1) | |
.split(",")) | |
.map(String::trim) | |
.mapToInt(Integer::parseInt) | |
.toArray(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment