如何使用流从另一个 HashMap 填充一个 HashMap

How to fill a HashMap from another HashMap using streams

我正在尝试从填充的 HashMap 应用 Java 流创建一个新的 Hashmap> 并且我一直在接收 java.util.HashMap$Node 无法转换为 class java.util.Map,我看不出问题所在。

可能有更简单、更合乎逻辑的方法,但这就是我想出的方法


Map<String, Product> hashMapChild = new HashMap<>();

hashMapChild.put("PC000123", new Product("reference1", "product1", price1));
hashMapChild.put("PC000234", new Product("reference2", "product2", price2));


Map<Integer, Map<String, Product>> hashMapParent = hashMapChild.entrySet()
                .stream()
                .collect(HashMap<Integer, Map<String, Product>>::new,
                         (map, streamValue) -> map.put((int) Math.floor(Math.random()*100),(Map<String, Product>) streamValue),
                                    
                         (map, map2) -> {
                             System.out.println(map);
                             System.out.println(map2);
                         });
        
        hashMapParent.forEach((k, v) -> System.out.println(k + ":" + v));

另一方面。如何获得自动增量索引而不是随机值?

非常感谢

输出可能是这样的:

<1, <COMPGAM012, Product{reference='COMPGAM012', name='laptop', prize=750.56}>>
<2, <PC000124, Product{reference='PC000124', name='Desktop', prize=400.56}>>

根据您提供的代码,hashMapChild 包含 2 个数据,并且根据为 hashMapParent 定义的结构,它应该将整个 hashMapChild 作为 hashMapParent 的值。例如:

Map<String, Product> hashMapChild = new HashMap<>();
hashMapChild.put("PC000123", new Product("reference1", "product1", price1));
hashMapChild.put("PC000234", new Product("reference2", "product2", price2));

Map<Integer, Map<String, Product>> hashMapParent = new HashMap<>();
hashMapParent.put(0, hashMapChild);

从代码来看,您似乎只有一个 hashMapChild 将包含所有产品,所以我认为在这种情况下您不需要进行任何类型的迭代。

或者我是否应该考虑添加更多这样的地图 Map<String, Product> hashMapChild = new HashMap<>(); 并将它们添加到 hashMapParent 中,例如:

hashMapParent.put(0, hashMapChild);
hashMapParent.put(1, hashMapChild1);
hashMapParent.put(2, hashMapChild2);

我的理解是,您想为地图中的每个条目分配一个索引。 所以,你想要的结果不是Map<Integer, Map<String, Product>>。其实你想要 Map<Integer, Map.Entry<String, Product>>.

对于索引,您可以使用 AtomicInteger

AtomicInteger index = new AtomicInteger(1);

Map<Integer, Map.Entry<String, Product>> hashMapParent = hashMapChild.entrySet()
                .stream()
                .collect(HashMap<Integer, Map.Entry<String, Product>>::new,
                        (map, streamValue) -> map.put(index.getAndIncrement(), streamValue),

                        (map, map2) -> {
                            System.out.println(map);
                            System.out.println(map2);
                        });

简化版:

Map<Integer, Map.Entry<String, String>> hashMapParent = hashMapChild.entrySet()
                .stream()
                .collect(Collectors.toMap(
                        k -> index.getAndIncrement(),
                        v -> v
                ));