groupby,sort,在java中对组进行排序

ki0zmccv  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(398)

关闭。这个问题需要细节或清晰。它目前不接受答案。
**想改进这个问题吗?**通过编辑这个帖子来添加细节并澄清问题。

23天前关门了。
改进这个问题
我有如下数据,并希望应用分组方式,排序组内,最后排序组。

1.2   5
1.3   5
1.5   4
2.1   4
2.2   4
3.5   4

通过使用Java8集合,我想按第二列数据分组并对第一列数据排序。稍后,我想自己对组进行排序。
下面是我预期的数据

1.3   5
1.2   5
3.5   4
2.2   4
2.1   4
1.5   4
ftf50wuq

ftf50wuq1#

您只需运行下面的单行方法即可根据需要对其进行排序

public static void sortGroup(List<Group> list) {
    list.sort(Comparator.comparingInt(Group::getCol2)
                        .thenComparing(Group::getCol1)
                        .reversed());
}

在这里 listList<Group> .
我们使用 Compartors 订购 col2 然后 col1 按升序排列。最后 reversed() 反转总顺序。
我假设 Group 结构如下

private static class Group {
        double col1;
        int col2;

        public Group(double col1, int col2) {
            this.col1 = col1;
            this.col2 = col2;
        }

        public double getCol1() {
            return col1;
        }

        public int getCol2() {
            return col2;
        }

        @Override
        public String toString() {
            return col1 + "\t" + col2;
        }
    }

测试:

public static void main(String[] args) {
    List<Group> list = Arrays.asList(
            new Group(1.2, 5),
            new Group(1.3, 5),
            new Group(1.5, 4),
            new Group(2.1, 4),
            new Group(2.2, 4),
            new Group(3.5, 4));
    sortGroup(list);
    list.forEach(System.out::println);
}

输出:

1.3 5
1.2 5
3.5 4
2.2 4
2.1 4
1.5 4

相关问题