[英]get count after using groupingBy condition on multiple fileds
我想在多个字段上使用groupingBy条件后获取userId的计数
我的模特班。
public class ModelClass{
int bussAssId;
int trackingId;
int userId;
int month;
String day;
int hour;
String deviceType ;
//Setter and Getters
}
在使用JpaRepositroy的服务类中,我正在获取数据列表。 这里usedId可以相同,但trackingId将是唯一的。
List<ModelClass> sqlModelList=postgreSQLRepository.findByBussAssId(bussAssId);
在这里我想使用groupingBy条件来表示月份,日期,小时,设备类型并获取userId的计数。
类似于:
select month,day,hour,device_type,PPC_TYPE,click_source,count(user_id) from ne_tracking_info group by month,day,hour,device_type;
我使用以下代码进行分组,但不了解如何排序。
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())))));
输出应如下所示:
您需要先对数据进行分组,然后对它们进行排序:
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());
在第一次收集( grouping
)之后,将计数值添加到对象中,然后对对象进行排序并收集到列表中。
这使用一个自定义对象来表示分组的数据:
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);
}
}
结果将是按计数降序排列的groupModels
列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.