I want to get counts of userId after using groupingBy condition on multiple fields
my model class.
public class ModelClass{
int bussAssId;
int trackingId;
int userId;
int month;
String day;
int hour;
String deviceType ;
//Setter and Getters
}
in service class using JpaRepositroy I am getting List of Data. Here usedId can be same but trackingId will be unique.
List<ModelClass> sqlModelList=postgreSQLRepository.findByBussAssId(bussAssId);
here I want to use groupingBy condition for month,day,hour,deviceType and get count of userId.
similer to:
select month,day,hour,device_type,PPC_TYPE,click_source,count(user_id) from ne_tracking_info group by month,day,hour,device_type;
I used following code for grouping but not understanding how to sort.
Map<Integer,Map<String,Map<Integer,Map<String,List<PostgreSQLModel>>>>> device=sqlModelList.stream().collect(Collectors.groupingBy(p->p.getMonth(),Collectors.groupingBy(p->p.getDay(),Collectors.groupingBy(p->p.getHour(),Collectors.groupingBy(p->p.getPrimaryKeys().getDeviceType())))));
the output should be like below:
You need to group the data first and sort them afterwards:
List<GroupModelClass> devices = sqlModelList.stream()
.collect(Collectors.groupingBy(GroupModelClass::new, Collectors.counting()))
.entrySet().stream()
.map(e -> e.getKey().setCount(e.getValue()))
.sorted(Comparator.comparingLong(GroupModelClass::getCount).reversed())
.collect(Collectors.toList());
After the first collect ( grouping
) the count value is added to the objects, the objects are sorted and collected to a list.
This uses a custom object to represent the grouped data:
public static class GroupModelClass {
private int month;
private String day;
private int hour;
private String deviceType;
private long count;
public GroupModelClass(ModelClass model) {
this.month = model.getMonth();
this.day = model.getDay();
this.hour = model.getHour();
this.deviceType = model.getDeviceType();
}
public GroupModelClass setCount(long count) {
this.count = count;
return this;
}
// getter
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GroupModelClass that = (GroupModelClass) o;
return month == that.month &&
hour == that.hour &&
count == that.count &&
Objects.equals(day, that.day) &&
Objects.equals(deviceType, that.deviceType);
}
}
The result will be a list of groupModels
sorted descending by count.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.