我有这张地图:
static Map<String, String> myMap = new HashMap<>();
static {
myMap.put("param1","param11");
myMap.put("param2","param22");
}
我有这个2d数组:
Object[][] objArr1 = new Object[][]{
{"1", 1},
{"2", 2}
};
我想&#34;合并&#34;上面进入另一个2d数组:
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];
但是无法创建适当的嵌套for循环来执行此操作。我试图将here和here的解决方案结合起来,但无济于事。 非常感谢任何帮助。
答案 0 :(得分:2)
这应该有用 它遍历数组的所有行以及地图的所有键/值对,并将它们组合在一个新行中。然后将每一行放在输出数组中。
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 param1 param11
1 1 param2 param22
2 2 param1 param11
2 2 param2 param22
答案 1 :(得分:0)
我需要一个Object[][]
作为TestNg @DataPovider
的最终产品,但由于数组固定大小,我无法解决问题。因此,我使用列表列表进行所有操作,并作为最后一步将其转换为2d数组:
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]