繁体   English   中英

Java 流 - 将列表排序为列表的 HashMap

[英]Java stream - Sort a List to a HashMap of Lists

假设我有一个Dog课程。

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

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

我想获得ListMap

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

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

我该怎么做?

您可以使用groupingBy来做到这一点。

假设您的输入是List<Dog> ,则Dog类中的Map成员称为map ,并且 Breed 存储为“Breed”键:

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

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

List<Dog> dogs = ...
Map<String, List<Dog>> map = dogs.stream()
     .collect(Collectors.groupingBy(Dog::getBreed)); 
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);
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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM