Skip to content

Instantly share code, notes, and snippets.

@sureshsarda
Created April 15, 2020 03:52
Show Gist options
  • Save sureshsarda/565550fbed856661a6c4a90ac817a2dd to your computer and use it in GitHub Desktop.
Save sureshsarda/565550fbed856661a6c4a90ac817a2dd to your computer and use it in GitHub Desktop.
Convert String to Integer and 2D Integer Array
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