【问题标题】:Java stream - Sort a List to a HashMap of ListsJava 流 - 将列表排序为列表的 HashMap
【发布时间】:2015-03-19 19:09:09
【问题描述】:

假设我有一个Dog 课程。

在其中我有一个Map<String,String>,其中一个值是Breed

public class Dog {
    String id;
    ...
    public Map<String,String>
}

我想得到MapLists:

HashMap<String, List<Dog>> // breed to a List<Dog>

我更喜欢使用 Stream 而不是迭代它。

我该怎么做?

【问题讨论】:

    标签: java java-8 hashmap java-stream


    【解决方案1】:
    List<Map<String,Object>> inAppropWords = new ArrayList<>();
        Map<String, Object> s = new HashMap<String, Object>();
        s.put("type", 1);
        s.put("name", "saas");
        Map<String, Object> s1 = new HashMap<String, Object>();
        s1.put("type", 2);
        s1.put("name", "swwaas");
        Map<String, Object> s2 = new HashMap<String, Object>();
        s2.put("type", 1);
        s2.put("name", "saqas");
        inAppropWords.add(s);
        inAppropWords.add(s1);
        inAppropWords.add(s2);
        
        Map<Integer, List<String>> t = inAppropWords.stream().collect(Collectors.groupingBy(d -> AppUtil.getInteger(d.get("type")),Collectors.mapping(d -> String.valueOf(d.get("name")),Collectors.toList())));
        System.out.println(t);
    

    【讨论】:

    • 如果要根据任意key采集数据,获取list中对应的其他key值
    【解决方案2】:
    List<Map<String , String>> as = new ArrayList<>();
            Map<String, String> a = new HashMap<>();
            a.put("key", "1");
            a.put("val", "ssd");
            Map<String, String> b = new HashMap<>();
            b.put("key", "1");
            b.put("val", "ssaad");
            Map<String, String> c = new HashMap<>();
            c.put("key", "2");
            c.put("val", "ssddad");
            Map<String, String> d = new HashMap<>();
            d.put("key", "2");
            d.put("val", "ssdfd");
            
            as.add(a);
            as.add(b);
            as.add(c);
            as.add(d);
            
            Map<String, List<String>> x = as.stream().collect(Collectors.groupingBy(i -> i.get("key"),
                    Collectors.mapping(k -> k.get("val"), Collectors.toList())));
            
            System.out.println(x);
    

    【讨论】:

      【解决方案3】:

      您可以使用groupingBy 来完成。

      假设您的输入是List&lt;Dog&gt;,则Dog 类中的Map 成员称为map,并为“品种”键存储品种:

      List<Dog> dogs = ...
      Map<String, List<Dog>> map = dogs.stream()
           .collect(Collectors.groupingBy(d -> d.map.get("Breed")));
      

      【讨论】:

        【解决方案4】:

        上面的好答案可以通过方法引用符号进一步改进:

        List<Dog> dogs = ...
        Map<String, List<Dog>> map = dogs.stream()
             .collect(Collectors.groupingBy(Dog::getBreed)); 
        

        【讨论】:

        • 我猜HashMap应该换成Map,否则项目语言级别较低的IDE会报错。
        猜你喜欢
        • 2012-07-02
        • 1970-01-01
        • 2016-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-17
        • 2021-04-19
        • 1970-01-01
        相关资源
        最近更新 更多