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. 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. 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.

How can I achieve that? I tried using filter() on a stream() on this List<UsersContexts> object, but without effort…

Answer

The first step is to collect UsersContexts into Map<Integer, List<Integer>> using Collectors.groupingBy grouping by on id. And then stream that map and convert each entry into 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());

Leave a Reply

Your email address will not be published. Required fields are marked *