[英](Java) Populate a 2d array with contents from another 2d array AND a map
我有这张地图:
static Map<String, String> myMap = new HashMap<>();
static {
myMap.put("param1","param11");
myMap.put("param2","param22");
}
我有这个二维数组:
Object[][] objArr1 = new Object[][]{
{"1", 1},
{"2", 2}
};
我想将上述内容“合并”到另一个二维数组中:
Object[][] objArr3 = new Object[][];
所以objArr3的结果内容是(没有特定的顺序):
{"1", 1, "param1","param11"},
{"1", 1, "param2","param22"},
{"2", 2,"param1","param11"},
{"2", 2,"param2","param22"
我明白我可能需要
new Object[objArr1 * myMap.size()][4];
这应该有效。
它遍历数组的所有行和映射的所有键/值对,将它们组合在一个新行中。 然后将每一行放入输出数组中。
static Map<String, String> map1 = new HashMap<>();
static {
map1.put("param1","param11");
map1.put("param2","param22");
}
static Object[][] array1 = new Object[][]{
{"1", 1},
{"2", 2}
};
public static void main (String[] args) throws java.lang.Exception
{
// the new array has precisely N*M rows
// where N is the number of rows in the input array
// and M is the number of entries in the map
Object[][] newArray = new Object[array1.length * map1.size()][4];
int index = 0;
for(int row=0;row<array1.length;row++)
{
for(Map.Entry<String, String> en : map1.entrySet())
{
Object[] newRow = new Object[4];
newRow[0] = array1[row][0];
newRow[1] = array1[row][1];
newRow[2] = en.getKey();
newRow[3] = en.getValue();
newArray[index] = newRow;
index++;
}
}
}
如果我然后输出数组,我得到
1 1 参数1 参数11
1 1 参数2 参数22
2 2 参数1 参数11
2 2 参数2 参数22
我需要一个Object[][]
作为 TestNg 的@DataPovider
的最终产品,但由于数组的大小固定,我无法解决问题。 因此,我使用列表列表进行所有操作,并作为最后一步将其转换为二维数组:
public class main {
static Map<Object, Object> myMap = new HashMap<>();
static {
myMap.put("1","1");
myMap.put("2","2");
myMap.put("3","3");
}
public static void main(String[] args){
List<List<Object>> list = asList(
asList("param1", "param11"),
asList("param2", "param22")
);
Object[][] finaList = mergeListWithMap(list, myMap);
System.out.println(Arrays.deepToString(finaList));
}
private static Object[][] mergeListWithMap(List<List<Object>> list, Map<Object, Object> myMap) {
List<List<Object>> newList = new ArrayList<>();
for(List<Object> o : list){
for(Map.Entry<Object, Object> en : myMap.entrySet()){
List<Object> nl = new ArrayList<>(o); // copy original containing "param<x>", "param<xx>"
nl.add(en.getKey()); // append
nl.add(en.getValue()); // append
newList.add(nl); // add final result to new list to be returned
}
}
// Convert list of lists -> 2d-array
Object[][] finaList = newList.stream()
.map(l -> l.stream().toArray(Object[]::new))
.toArray(Object[][]::new);
return finaList;
}
private static <T> List<T> asList(T ... items) {
List<T> list = new ArrayList<>();
for (T item : items) {
list.add(item);
}
return list;
}
}
输出:
[param1, param11, 1, 1]
[param1, param11, 2, 2]
[param1, param11, 3, 3]
[param2, param22, 1, 1]
[param2, param22, 2, 2]
[param2, param22, 3, 3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.