假设我有一个Dog
课程。
在其中我有一个Map<String,String>
,其中一个值为Breed
。
public class Dog {
String id;
...
public Map<String,String>
}
我希望Map
获得List
:
HashMap<String, List<Dog>> // breed to a List<Dog>
我更喜欢使用Stream
而不是迭代它。
我该怎么办?
答案 0 :(得分:58)
您可以使用groupingBy
。
假设您的输入为List<Dog>
,则Map
类中的Dog
成员称为map
,并为&#34; Breed&存储品种#34;关键:
List<Dog> dogs = ...
HashMap<String, List<Dog>> map = dogs.stream()
.collect (Collectors.groupingBy(d -> d.map.get("Breed")));
答案 1 :(得分:29)
使用函数式编程符号可以进一步改善上面的好答案:
List<Dog> dogs = ...
HashMap<String, List<Dog>> map = dogs.stream()
.collect(Collectors.groupingBy(Dog::getBreed));
答案 2 :(得分:0)
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 :(得分:0)
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);