[英]How to create a list of distinct objects using list of different objects having properties using java streams
I have an algorythmic problem with creating something logical for a set of data like this:我在为这样的一组数据创建逻辑时遇到了一个算法问题:
|-------|--------|
| id | ctx_id |
|-------|--------|
| 1 | 1001 |
| 1 | 1002 |
| 1 | 1003 |
| 1 | 1004 |
| 2 | 2001 |
| 2 | 2002 |
| 2 | 2003 |
------------------
This is the list I get from the database, as an List<UsersContexts>
object containing the id
and ctx_id
.这是我从数据库中获取的列表,作为包含
id
和ctx_id
的List<UsersContexts>
对象。 What I want to achieve, is to create two objects of such entity:我想要实现的是创建这样的实体的两个对象:
private class UserData {
private long id;
private List<long> contextList;
}
Every user has an ID, and contexts assigned to him.每个用户都有一个 ID 和分配给他的上下文。 What I want to achieve is to manipulate the data in table above so I can create two
UserData
object, the one containing id = 1
and a list containg 1001, 1002, 1003, 1004
, and a second UserData
object, containing id = 2
and a list containing 2001, 2002, 2003
.我想要实现的是操作上表中的数据,以便我可以创建两个
UserData
对象,一个包含id = 1
和一个包含1001, 1002, 1003, 1004
的列表,以及第二个UserData
对象,包含id = 2
和包含2001, 2002, 2003
的列表。
How can I achieve that?我怎样才能做到这一点? I tried using
filter()
on a stream()
on this List<UsersContexts>
object, but without effort...我尝试在这个
List<UsersContexts>
对象上的stream()
上使用filter()
,但毫不费力......
The first step is to collect UsersContexts
into Map<Integer, List<Integer>>
using Collectors.groupingBy grouping by on id
.第一步是使用Collectors.groupingBy按
id
分组将UsersContexts
收集到Map<Integer, List<Integer>>
。 And then stream that map and convert each entry into UserData
然后流式传输该映射并将每个条目转换为
UserData
usersContexts.stream()
.collect(Collectors.groupingBy(UsersContexts::getId,
Collectors.mapping(UsersContexts::getCxtId, Collectors.toList())))
.entrySet()
.stream()
.map(entry->new UserData(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
You can use map()
function and toMap()
collectors with merge function.您可以将
map()
函数和toMap()
收集器与合并函数一起使用。
Collectio<UserData> usersData = usersContexts.stream()
.map(u -> new UserData(u.getId(), new ArrayList<>(singletonList(u.getCtx_id()))))
.collect(Collectors.toMap(UserData::getId, Function.identity(),
(o, o2) -> { o.getContextList().addAll(o2.getContextList());return o; }))
.values();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.