如何使用 java 流使用具有属性的不同对象列表创建不同对象列表

How to create a list of distinct objects using list of different objects having properties using java streams

我在为一组数据创建逻辑问题时遇到了算法问题:

|-------|--------|
|  id   | ctx_id |
|-------|--------|
|   1   |  1001  |
|   1   |  1002  |
|   1   |  1003  |
|   1   |  1004  |
|   2   |  2001  |
|   2   |  2002  |
|   2   |  2003  |
------------------

这是我从数据库中获取的列表,作为包含 idctx_idList<UsersContexts> 对象。我想要实现的是创建此类实体的两个对象:

private class UserData {
    private long id;
    private List<long> contextList;
}

每个用户都有一个 ID 和分配给他的上下文。我想要实现的是操作上面 table 中的数据,这样我就可以创建两个 UserData 对象,一个包含 id = 1 和一个包含 1001, 1002, 1003, 1004 的列表,第二个UserData 对象,包含 id = 2 和包含 2001, 2002, 2003.

的列表

我怎样才能做到这一点?我尝试在这个 List<UsersContexts> 对象的 stream() 上使用 filter(),但没有任何努力...

第一步是使用 id 上的 Collectors.groupingBy 分组将 UsersContexts 收集到 Map<Integer, List<Integer>> 中。然后流式传输该映射并将每个条目转换为 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());

您可以使用 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();