[英]using java 8 to group list of object by object attribute of type list: JAVA
I have an Object like我有一个像
public class User {
private String id;
private List<String> brands_ids;
}
and I have a list of User objects like: example data我有一个用户对象列表,例如:示例数据
[
{
"id": 1,
"brands_ids": [
10,
20,
30
]
},
{
"id": 2,
"brands_ids": [
10,
50
]
},
{
"id": 3,
"brands_ids": [
10,
80
]
}
]
My Question is, How to Group this list to know in which objects the brand id appears, for example brand id=10 appears in all three objects, the brand id=30 only in one object我的问题是,如何对该列表进行分组以了解品牌 id 出现在哪些对象中,例如品牌 id=10 出现在所有三个对象中,品牌 id=30 仅出现在一个对象中
a result of a map with key=brand id and value = count would solve my issue something like this: {10:3},{20:1},{30,1},{50,1},{80,1}具有 key=brand id 和 value = count 的地图的结果将解决我的问题,如下所示:{10:3},{20:1},{30,1},{50,1},{80,1 }
Take a look here and here看看这里和这里
This code fragment create 3 users, like in your example.这个代码片段创建了 3 个用户,就像你的例子一样。
var users = Arrays.asList(
new User("1", Arrays.asList("10", "20", "30")),
new User("2", Arrays.asList("10", "50")),
new User("3", Arrays.asList("10", "80")));
Map<String, Long> result = users
.stream()
.flatMap(user -> user.getBrand_ids().stream())
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(result);
// Result is: {80=1, 50=1, 30=1, 20=1, 10=3}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.