我有一个像这样的对象
public class User {
private String id;
private List<String> brands_ids;
}
我有一个 User 对象列表,例如: 示例数据
[
{
"id": 1,
"brands_ids": [
10,
20,
30
]
},
{
"id": 2,
"brands_ids": [
10,
50
]
},
{
"id": 3,
"brands_ids": [
10,
80
]
}
]
我的问题是,如何对此列表进行分组以了解品牌 id 出现在哪些对象中,例如品牌 id=10 出现在所有三个对象中,品牌 id=30 仅出现在一个对象中
带有 key=brand id 和 value=count 的 map 结果可以解决我的问题 像这样:{10:3},{20:1},{30,1},{50,1},{80,1}
最佳答案
此代码片段创建 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}
关于java - 使用java 8按类型列表: JAVA的对象属性对对象列表进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60064970/