编程语言
首页 > 编程语言> > Java8Stream数字和NULL如何排序

Java8Stream数字和NULL如何排序

作者:互联网

case

List<Persion> list=new ArrayList<>();
        list.add(new Persion(null,"a",2));
        list.add(new Persion(null,"b",2));
        list.add(new Persion(null,"c",3));
        list.add(new Persion(null,"d",3));
        list.add(new Persion(null,"e",null));

        list.stream()
                .sorted(Comparator.comparing(Persion::getId).thenComparing(Persion::getAge))
                .forEach(System.out::println);

因为有null的存在,可能会出现空指针异常

at java.util.Comparator.lambda$comparing$77a9974f$1(Comparator.java:469)
	at java.util.Comparator.lambda$thenComparing$36697e65$1(Comparator.java:216)
	at java.util.TimSort.countRunAndMakeAscending(TimSort.java:355)
	at java.util.TimSort.sort(TimSort.java:220)
	at java.util.Arrays.sort(Arrays.java:1512)
	at java.util.stream.SortedOps$SizedRefSortingSink.end(SortedOps.java:348)
	at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)

解决方案:
A:(不推荐使用哦,因为会更改原本的数据)
使用peek给它set一个数字,再去排序

List<Persion> list=new ArrayList<>();
        list.add(new Persion(1,"a",null));
        list.add(new Persion(1,"b",2L));
        list.add(new Persion(2,"c",3L));
        list.add(new Persion(4,"d",null));
        list.add(new Persion(3,"e",1L));

        list.stream()
                .peek(a->{
                    if (a.getAge()==null){
                        a.setAge(-1L);
                    }
                })
                .sorted(Comparator.comparing(Persion::getId).
                        thenComparing(Persion::getAge,Comparator.reverseOrder()).
                        thenComparing(Persion::getName))
                .forEach(System.out::println);

B:推荐使用,不会更改原有数据:

public static void main(String[] args) {
        List<Persion> list=new ArrayList<>();
        list.add(new Persion(1,"a",null));
        list.add(new Persion(1,"b",2));
        list.add(new Persion(2,"c",3));
        list.add(new Persion(4,"d",null));
        list.add(new Persion(3,"e",1));
//
        list.stream()
                .sorted(Comparator.comparing(Persion::getId).
                        thenComparing(Persion::getAge,Comparator.nullsFirst(Integer::compareTo)).
                        thenComparing(Persion::getName))
                        .forEach(System.out::println);
    }
//结果:
Persion(id=1, name=a, age=null)
Persion(id=1, name=b, age=2)
Persion(id=2, name=c, age=3)
Persion(id=3, name=e, age=1)
Persion(id=4, name=d, age=null)

标签:Java8Stream,java,null,list,add,排序,new,Persion,NULL
来源: https://blog.csdn.net/John_D_B_Lee/article/details/118769559