[英]Java stream - Sort a List to a HashMap of Lists
Let's say I have a Dog
class.假设我有一个Dog
课程。
Inside it I have a Map<String,String>
and one of the values is Breed
.在它里面我有一个Map<String,String>
,其中一个值是Breed
。
public class Dog {
String id;
...
public Map<String,String>
}
I want to get a Map
of List
s:我想获得List
的Map
:
HashMap<String, List<Dog>> // breed to a List<Dog>
I'd prefer to use a Stream
rather than iterating it.我更喜欢使用Stream
而不是迭代它。
How can I do it?我该怎么做?
You can do it with groupingBy
.您可以使用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>
,则Dog
类中的Map
成员称为map
,并且 Breed 存储为“Breed”键:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.