我有如下所示的数据,并希望应用组,在组内排序,最后对组进行排序。
1.2 5
1.3 5
1.5 4
2.1 4
2.2 4
3.5 4通过使用java 8集合,我希望按第二列数据分组,并对第一列数据进行排序。稍后,我想自己对组进行排序。
下面是我所期望的数据
1.3 5
1.2 5
3.5 4
2.2 4
2.1 4
1.5 4发布于 2020-12-17 08:42:43
只需要运行下面的单行方法就可以根据需要对其进行排序。
public static void sortGroup(List<Group> list) {
list.sort(Comparator.comparingInt(Group::getCol2)
.thenComparing(Group::getCol1)
.reversed());
}这里的List<Group>.
list是使用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 4https://stackoverflow.com/questions/65336756
复制相似问题