java8对集合排序,多字段排序(升序和降序)(空值排到最后)

本文展示了如何使用Java对Student对象列表进行排序,包括按id(升序和降序,空值排最后)、按id降序和名字升序的复杂排序操作,使用了Comparator和AlibabaFastjson库.
摘要由CSDN通过智能技术生成

对集合排序,多字段排序(升序和降序)(空值排到最后)

数据准备 排序

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class Student {
    private Long id;
    private String name;
    private int classNum;
}
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class SortTest {

    public static void main(String[] args) {
        Student student4 = new Student();
        //student4.setId("4");
        student4.setName("4");
        student4.setClassNum(4);
        Student student5 = new Student();
        student5.setId(66l);
        student5.setName("5");
        student5.setClassNum(4);
        Student student1 = new Student();
        student1.setId(11l);
        student1.setName("5");
        student1.setClassNum(4);
        Student student2 = new Student();
        student2.setId(44l);
        student2.setName("5");
        student2.setClassNum(4);
        Student student3 = new Student();
        student3.setId(334l);
        student3.setName("5");
        student3.setClassNum(4);
        Student student6 = new Student();
        student6.setId(44L);
        student6.setName("4");
        student6.setClassNum(3);
        List<Student> list2 = new ArrayList();
        list2.add(student4);
        list2.add(student5);
        list2.add(student6);
        list2.add(student1);
        list2.add(student2);
        list2.add(student3);
        System.out.println(list2);

        List list3 = list2.stream().sorted(Comparator.comparing(Student::getId,Comparator.nullsFirst(Long::compareTo)).reversed())
                .collect(Collectors.toList());
        //倒叙

        String s1 = JSON.toJSONString(list3);
        System.out.println(s1);

        List list4 = list2.stream().sorted(Comparator.comparing(Student::getId,Comparator.nullsLast(Long::compareTo)))
                .collect(Collectors.toList());//升序

        List list5 = list2.stream().sorted(Comparator.comparing(Student::getId,Comparator.nullsLast(Long::compareTo))
                .reversed().thenComparing(Student::getName,Comparator.nullsLast(String::compareTo)))
                .collect(Collectors.toList());//id降序,名字升序


        String s2 = JSON.toJSONString(list4);
        System.out.println(s2);
        String s3 = JSON.toJSONString(list5);
        System.out.println(s3);
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值