I have a 2D array that contains as such
String[][] twodarray = { { "grey", "value1", "beta" },
{ "r", "name", "gender" , "value", "Female" },
{ "r", "name", "gender", "value", "Male" },
{ "r", "name", "exp", "value", "1" },
{ "r", "name", "exp", "value", "2" },
{ "red", "value1", "alpha" },
{ "blue", "value2", "alpha" },
};
My goal is when there are 2 or more elements [a][0] and [a][2] are the same, it will group together and combine the elements as one.
For example, [1][0] and [2][0], r and [1][2] and [2][2], gender are the same.
Thus, it will combine into one as shown below.
{ "r", "name", "gender" , "value", "Female", "Male" },
Thus, my desired output is as follow
final output:
results = { { "grey", "value1", "beta" },
{ "r", "name", "gender" , "value", "Female", "Male" },
{ "r", "name", "exp", "value", "1", "2" },
{ "red", "value1", "alpha" },
{ "blue", "value2", "alpha" },
};
What I have is as follow
for (int a=0; a < twodarray.length-1; a++)
{
if ((twodarray[a][0] == twodarray[a+1][0]) && (twodarray[a][2] == twodarray[a+1][2]))
}
}
My question is how can I combine the array as such?
Any help will be much appreciated.
First, I have collected the rows into a Map<List<String>, List<String>>
which groups final values (the last String) by the prefix (every String other than the last String). Then I collected the map entries back into a 2d String array format:
package samplejava;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class SampleJava {
public static void main(String[] args) {
String[][] twodarray = { { "grey", "value1", "beta" },
{ "r", "name", "gender" , "value", "Female" },
{ "r", "name", "gender", "value", "Male" },
{ "r", "name", "exp", "value", "1" },
{ "r", "name", "exp", "value", "2" },
{ "red", "value1", "alpha" },
{ "blue", "value2", "alpha" },
};
Map<List<String>, List<String>> groups;
groups = Arrays.stream(twodarray).collect(Collectors.groupingBy(
(String[] item)-> Arrays.asList(item).subList(0, item.length - 1),
Collectors.mapping(
(String[] item)-> item[item.length - 1],
Collectors.toList())));
String[][] result = groups.entrySet().stream()
.map(entry -> Stream.concat(entry.getKey().stream(),
entry.getValue().stream())
.toArray(String[]::new))
.toArray(String[][]::new);
for(String[] row: result) {
System.out.println(Arrays.toString(row));
}
}
}
This method, however, does not preserve the original order of items. But you did not say that was necessary.