Java教程

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数字和NULL如何排序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!