Comparator学习总结

2023-12-29 11:31:48
 List<Teach> list = new ArrayList<>();
        Teach teach1 = new Teach();
        Teach teach2 = new Teach();
        Teach teach3 = new Teach();
        Teach teach4 = new Teach();
        teach1.setName("赵大");
        teach1.setAge(20);

        teach2.setName("钱二");
        teach2.setAge(19);

        teach3.setName("孙三");
        teach3.setAge(null);

        teach3.setName("李四");
        teach3.setAge(17);


        list.add(teach1);
        list.add(teach2);
        list.add(teach3);
        list.add(teach4);

?

List<Teach> list1 = list.stream().sorted(Comparator.comparing(Teach::getAge)).collect(Collectors.toList());


Exception in thread "main" java.lang.NullPointerException
	at java.util.Comparator.lambda$comparing$77a9974f$1(Comparator.java:469)
	at java.util.TimSort.countRunAndMakeAscending(TimSort.java:356)
	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)
	at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
	at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
	at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
	at com.example.demo.TestTeach.main(TestTeach.java:34)

?

?通过nullsFirst或者nullsLast可以兼容null值

    //[Teach{name='null', age=null}, Teach{name='李四', age=17}, Teach{name='钱二', age=19}, Teach{name='赵大', age=20}]
        List<Teach> list1 = list.stream().sorted(Comparator.comparing(Teach::getAge ,
                Comparator.nullsFirst(Integer::compare))).collect(Collectors.toList());

?对结果取反


        //[Teach{name='赵大', age=20}, Teach{name='钱二', age=19}, Teach{name='李四', age=17}, Teach{name='null', age=null}]
        List<Teach> list1 = list.stream().sorted(Comparator.comparing(Teach::getAge ,
                Comparator.nullsFirst(Integer::compare)).reversed()).collect(Collectors.toList());

?

?

文章来源:https://blog.csdn.net/riju4713/article/details/135283531
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。