简体   繁体   中英

Java stream - Sort a List to a HashMap of Lists

Let's say I have a Dog class.

Inside it I have a Map<String,String> and one of the values is Breed .

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

I want to get a Map of List s:

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

I'd prefer to use a Stream rather than iterating it.

How can I do it?

You can do it with groupingBy .

Assuming that your input is a List<Dog> , the Map member inside the Dog class is called map , and the Breed is stored for the "Breed" key :

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

The great answer above can further be improved by method reference notation:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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