java - 在多个字段上使用 groupingBy 条件后获取计数

标签 java java-8 java-stream

我想在多个字段上使用 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);

这里我想对月、日、小时、设备类型使用分组条件并获取 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())))));

输出应如下所示:

output exampe

最佳答案

您需要先对数据进行分组,然后再对它们进行排序:

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());

第一次收集(分组)后,计数值将添加到对象中,对对象进行排序并收集到列表中。

这使用自定义对象来表示分组数据:

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 列表。

关于java - 在多个字段上使用 groupingBy 条件后获取计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54803680/

相关文章:

java - 有没有更好的方法可以使用 Stream 进行编写?

java - 流 : Calculate the difference of totals in one go

java - 为什么 Stream.allMatch() 为空流返回 true?

java - Scala 方式来初始化成员?

java - 直接从字符串创建流

java - Android - 在没有应用程序上下文的情况下获取用户 GPS 位置

java - 是否可以检查所有 Java 8 流元素是否满足给定谓词之一?

无法识别 Java XX 命令行选项(例如 : -XX:+UseStringDeduplication, -XX:MaxGCPauseMillis)

java - undefined variable "images"Matlab编译代码错误

java - Hazelcast 内置的 CountAggregation 真的效率低下吗?