I've got a String[]
with values that need to be put into a String[][]
with each "row" consisting of the current index and the value of the former array. An iterative solution looks like this:
String[] vals = getValsFromSomewhere();
String[][] targetArray = new String[vals.length][];
for (int i = 0; i < targetArray.length; i++) {
targetArray[i] = new String[]{
Integer.toString(i), vals[i]
};
}
I currently try to change that to streams to avoid temporary variables and get rid off for-loops throughout my method but the best solution I came up with so far is:
String[] vals = getValsFromSomewhere();
String[][] targetArray = IntStream.range(0, vals.length)
.mapToObj(index -> new String[]{
Integer.toString(index), vals[index]
})
.toArray(String[][]::new);
It's a solution with streams, all right. But part of my original goals, to get rid off temporary variables (vals
in this case), isn't achieved. Searching through available methods in Stream
hasn't brought up anything that looks useful but I might have missed something. That's why I'm asking here ;-) Pointing me to the right direction is highly appreciated.