list排序中经常是针对对象的某个字段排序,但是字段为null是处理起来比较麻烦,java中有针对此情况的api,下面做详细介绍。
代码案例
@TestpublicvoidtestListSort(){List<Book>bookList=newArrayList<>();bookList.add(newBook(null,"水浒传"));bookList.add(newBook(9,"钢铁怎样炼成的"));bookList.add(newBook(null,"百年孤独"));bookList.add(newBook(3,"三国演义"));bookList.add(newBook(18,"史记"));System.out.println("bookList = "+bookList);/* 整理升序,price为null的排在最后 */List<Book>bookList1=bookList.stream().sorted(Comparator.comparing(Book::getPrice,Comparator.nullsLast(Comparator.naturalOrder()))).collect(Collectors.toList());System.out.println("整理升序,price为null的排在最后:");System.out.println("bookList1 = "+bookList1);/* 整体升序,price为null的排在最前 */List<Book>bookList2=bookList.stream().sorted(Comparator.comparing(Book::getPrice,Comparator.nullsFirst(Comparator.naturalOrder()))).collect(Collectors.toList());System.out.println("整体升序,price为null的排在最前:");System.out.println("bookList2 = "+bookList2);/* 整体降序,price为null的排在最后 */List<Book>bookList3=bookList.stream().sorted(Comparator.comparing(Book::getPrice,Comparator.nullsLast(Comparator.reverseOrder()))).collect(Collectors.toList());System.out.println("整体降序,price为null的排在最后:");System.out.println("bookList3 = "+bookList3);/* 整体降序,price为null的排在最前 */List<Book>bookList4=bookList.stream().sorted(Comparator.comparing(Book::getPrice,Comparator.nullsFirst(Comparator.reverseOrder()))).collect(Collectors.toList());System.out.println("整体降序,price为null的排在最前");System.out.println("bookList4 = "+bookList4);}Book类
@NoArgsConstructor@AllArgsConstructor@DatapublicclassBook{privateIntegerprice;privateStringname;}运行结果
bookList=[Book(price=null,name=水浒传),Book(price=9,name=钢铁怎样炼成的),Book(price=null,name=百年孤独),Book(price=3,name=三国演义),Book(price=18,name=史记)]整理升序,price为null的排在最后:bookList1=[Book(price=3,name=三国演义),Book(price=9,name=钢铁怎样炼成的),Book(price=18,name=史记),Book(price=null,name=水浒传),Book(price=null,name=百年孤独)]整体升序,price为null的排在最前:bookList2=[Book(price=null,name=水浒传),Book(price=null,name=百年孤独),Book(price=3,name=三国演义),Book(price=9,name=钢铁怎样炼成的),Book(price=18,name=史记)]整体降序,price为null的排在最后:bookList3=[Book(price=18,name=史记),Book(price=9,name=钢铁怎样炼成的),Book(price=3,name=三国演义),Book(price=null,name=水浒传),Book(price=null,name=百年孤独)]整体降序,price为null的排在最前 bookList4=[Book(price=null,name=水浒传),Book(price=null,name=百年孤独),Book(price=18,name=史记),Book(price=9,name=钢铁怎样炼成的),Book(price=3,name=三国演义)]