Search code examples
javajava-stream

java how to return custom list instead of object list in stream from groupby method?


I have a entity with these fields

private Long id;

private String name;

private Boolean isStudent;

Now I can group list of entity like bellow

Map<Boolean, List<User>> result = userList.stream().collect(Collectors.groupingBy(User::getStudent));

But I am struggling to find out how can I return ID list instead of the whole User list like bellow

Map<Boolean, List<Long>> result = userList.stream().collect(Collectors.groupingBy(...));

I can apply stream again in the another line but is it possible to it in the same line with groupby?


Solution

  • You could map the grouped values by use the overloaded groupingBy with mapping methods

    Map<Boolean, List<Long>> result = userList.stream().collect(Collectors.groupingBy(User::getStudent, Collectors.mapping(User::getId, Collectors.toList())));