我如何填充一个没有双倍循环的哈希图的2D阵列



说我创建了一个2D阵列的哈希图:

Map<String,String>[][] matrix = new Map[5][10];

有没有一种方法可以在此矩阵中使用空的hashmaps填充每个条目,而无需进行标准double?

这是使用Arrays实用程序类的单线:

Arrays.stream(matrix).forEach(row -> Arrays.setAll(row, i -> new HashMap<>()));

让我们不要忘记另一个选项:数组初始化器:

Map<String, String>[][] = new Map[][] {
    {new HashMap<>(), ... 8 more like that..., new HashMap<>()},
       // 3 more lines like the one above... 
    {new HashMap<>(), ..., new HashMap<>() }
};

总共是50 new HashMap<>() s。双for循环现在看起来还不错,是吗?

for (int i = 0; i < 50; i++) {
    matrix[i / 10][i % 10] = new HashMap<>();
}

但是为什么?

最新更新