0

I have a code like below:

Pageable pageableRequest = PageRequest.of(page, limit, Sort.by(sortBy));
Page<User> userList= null;
userList = this.user.findAll(pageableRequest)

from here I get all the data and total is shown. However, I want to group the total by status. How can I achieve that? Now total is 26 and I have 3 status inactive, active and vip.

CloudSeph
  • 863
  • 4
  • 15
  • 36
  • `I want to group the total by status` by count, data? have you tried writing query? – bananas Mar 31 '20 at 07:37
  • I have tried something like below but it is only returning 3 values but I am not getting all user only one from each group @Query("SELECT u FROM User u GROUP BY status") Page findAll(); – CloudSeph Mar 31 '20 at 07:45

1 Answers1

0

If you want to have all users grouped by status you can do something like below.

Ask for all users and than group it in java

List<User> userList = this.user.findAll();
Map<Status, List<User>> mapResult = userList.stream()
    .collect(Collectors.groupingBy(User::getStatus));
lczapski
  • 4,026
  • 3
  • 16
  • 32
  • I need to return as Page. How can I accomplish this with the above? – CloudSeph Mar 31 '20 at 08:12
  • How it should looked like with `Page`. For example: with 25 users and page size 10? @CloudSeph – lczapski Mar 31 '20 at 08:27
  • 1
    You can use `Page` and do this `this.user.findAll(pageableRequest).stream() .collect(Collectors.groupingBy(User::getStatus));` but it only map for subList not all users @CloudSeph – lczapski Mar 31 '20 at 08:31
  • @Iczapski I can't do that. I will get incompatible types. – CloudSeph Mar 31 '20 at 10:15
  • @CloudSeph Where is 'incompatible types'? – lczapski Mar 31 '20 at 13:40
  • The above Page user = this.user.findAll(pageableRequest).stream() .collect(Collectors.groupingBy(User::getStatus)); – CloudSeph Mar 31 '20 at 13:48
  • this part is the one giving me the error. Incompatible types. Required User but collect was inferred to R: no instance of type variable .K, T exist so that Map> conforms to Page – CloudSeph Mar 31 '20 at 14:28