简体   繁体   English

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

[英]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 .这是我从数据库中获取的列表,作为包含idctx_idList<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.groupingByid分组将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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM