Java8Stream数字和NULL如何排序
2021/7/15 22:06:10
本文主要是介绍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如何排序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-14后台交互资料入门指南
- 2024-11-14如何轻松创建项目环境:新手入门教程
- 2024-11-14如何抽离公共代码:初级开发者指南
- 2024-11-14Python编程入门指南
- 2024-11-14Python编程入门:如何获取参数
- 2024-11-14JWT 用户校验:简单教程与实践
- 2024-11-14Pre-commit 自动化测试入门指南
- 2024-11-14Python编程基础
- 2024-11-14Server Action入门教程:轻松掌握服务器操作
- 2024-11-14Server Component入门教程:轻松搭建服务器组件