使用Java8 Stream API合并两个hashmap列表

问题描述 投票:3回答:3

我有两个Lists HashMap

List<HashMap<String,String>> a = new ArrayList<HashMap<String,String>>();
List<HashMap<String,String>> b = new ArrayList<HashMap<String,String>>();

样本数据:

a = [{a1=1, b1=2, c=3},{a2=4, b2=5, c=6}]
b = [{d1=7,c=3},{d2=8,c=6}]

我想合并两个Lists并使用具有输出的Stream API获得List的最终HashMap

c = [{a1=1, b1=2, c=3, d1=7},{a2=4, b2=5, c=6, d2=8}]

有帮助吗?

java collections java-8 java-stream
3个回答
2
投票

有时Stream API不是答案。在这种情况下,常规循环将更易读和可维护。您甚至可以在循环中添加注释来解释为什么它会在不使代码不可读的情况下执行某些操作。 Stream API使平凡的东西变得非常容易和复杂,甚至更复杂。

除非是家庭作业,否则这是一项愚蠢的家庭作业。学校工作不应该鼓励学生在错误的地方使用愚蠢的结构。

在现实世界中,可读性和可维护性对于行数或聪明度得分至关重要。


1
投票

如果你根据Lists'索引合并它们,并且两个Lists具有相同的长度,你可以写:

IntStream.range(0,a.size()).forEach(i->a.get(i).putAll(b.get(i)));

这将导致包含合并结果的List a

如果你想生产一个新的List而不改变原来的Lists,你可以创建新的HashMaps并将它们收集到一个新的List

List<HashMap<String,String>> c =
    IntStream.range(0,a.size())
             .mapToObj(i -> {
                        HashMap<String,String> hm = new HashMap<>(a.get(i)); 
                        hm.putAll(b.get(i)); 
                        return hm;
                      })
             .collect(Collectors.toList());

编辑更新的问题:

List<HashMap<String,String>> c =
    a.stream ()
     .map(am -> {
             HashMap<String,String> hm = new HashMap<>(am);
             HashMap<String,String> second =
               b.stream()
                .filter (bm -> bm.get ("c") != null && bm.get ("c").equals (am.get ("c")))
                .findFirst()
                .orElse(null);
             if (second != null) {
               hm.putAll (second);
             }
             return hm;
          })
    .collect(Collectors.toList());

现在我们流过第一个List和每个HashMap的元素,搜索第二个HashMap的相应List


0
投票

试试这样吧。为了简化它,我定义了一个双功能。

BiFunction<HashMap<String, String>, List<HashMap<String, String>>, HashMap<String, String>> biFunction =
            (m1, listOfMap) -> {
                HashMap<String, String> result = new HashMap<>(m1);
                listOfMap.forEach(item -> {
                    if (item.containsKey("c")&& item.get("c").equals(result.get("c")))
                    result.putAll(item);
                });
                return result;
            };

然后合并使用此BiFunction来合并List项。

IntStream.range(0, list.size())
            .mapToObj(i -> biFunction.apply(list.get(i), list2))
            .collect(Collectors.toList());
© www.soinside.com 2019 - 2024. All rights reserved.