I have an array of string
String[] outLines = ['1 2 3', '1 2 3', '1 2 3'];
What I want to do is extract all values of a certain column to a new array. For example, the first column array will contain [1, 1, 1]
. The second column array will contain [2, 2, 2]
etc.
My first though was to loop the string array, split every string using spaces and then add each value to its relevant column array.
I was wondering, is there a better way to do so? both performance and syntax wise.
CodePudding user response:
It sounds like you want to map the column values from the String
array. Java provides several implementations of Map
. The most applicable (imo) is LinkedHashMap
since it preserves insertion order. Split the line on whitespace, iterate; for each column retrieve the existing List
from the Map
(or add a new List
if one does not already exist). Something like,
String[] outLines = { "1 2 3", "1 2 3", "1 2 3" };
Map<Integer, List<String>> alMap = new LinkedHashMap<>();
List.of(outLines).forEach(s -> {
String[] line = s.split("\\s ");
for (int i = 0; i < line.length; i ) {
List<String> al = alMap.getOrDefault(i, new ArrayList<>());
al.add(line[i]);
alMap.put(i, al);
}
});
for (int key : alMap.keySet()) {
System.out.println(alMap.get(key));
}
Which outputs
[1, 1, 1]
[2, 2, 2]
[3, 3, 3]
CodePudding user response:
Wow ! It been while since last time I found this kind of questions!, there are many ways you can achieve your answer, consider one of them as follow with only four line of code.
String[] outLines = {"1 2 3", "1 2 3", "1 2 3"};
List<String[]> accumulator = new ArrayList<>();
Arrays.stream(outLines).map(o -> o.split(" ")).forEach(accumulator::add);
String[][] result = accumulator.toArray(String[][]::new);
//Validate the result
Arrays.stream(result).map(Arrays::stream).forEach(o -> {
System.out.println();
o.forEach(System.out::print);
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
You can also create a Collector and use the accumulator and combiner quit similar to what I wrote for you and reduce the answer to two line.
(Don't forget to Woot !)
CodePudding user response:
Try this.
static int[][] extract(String[] array) {
int rows = array.length, cols = array[0].split("\\s ").length;
int[][] matrix = new int[cols][rows];
for (int i = 0; i < rows; i) {
String[] s = array[i].split("\\s ");
for (int j = 0; j < cols; j)
matrix[j][i] = Integer.parseInt(s[j]);
}
return matrix;
}
public static void main(String[] args) {
String[] outLines = {"1 2 3", "1 2 3", "1 2 3"};
int[][] output = extract(outLines);
for (int[] row : output)
System.out.println(Arrays.toString(row));
}
output:
[1, 1, 1]
[2, 2, 2]
[3, 3, 3]