如何在没有double for循环的情况下使用hashmaps填充二维数组

时间:2018-04-04 00:59:34

标签: java performance multidimensional-array hashmap

假设我创建了一个二维数组的哈希映射:

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

有没有一种方法可以使用空哈希图填充此矩阵中的每个条目而不执行标准的双循环?

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

但为什么?

答案 2 :(得分:0)

让我们不要忘记另一个选择:数组初始值设定项:

for cpPtr in cpdomains:  
    domainKeys = self.domainSplitter(cpPtr.split(" ")[1])  
    for domainKey in domainKeys:
         domainAggregator[domainKey] = (
             domainAggregator.get(domainKey, 0) + int(cpPtr.split(" ")[0]))

共计50 Map<String, String>[][] = new Map[][] { {new HashMap<>(), ... 8 more like that..., new HashMap<>()}, // 3 more lines like the one above... {new HashMap<>(), ..., new HashMap<>() } }; 秒。双new HashMap<>()循环现在看起来不那么糟糕,是吗?