list stream sort Comparator.nullsLast 避免空指针的正确用法

list stream sort Comparator.nullsLast 避免空指针的正确用法
list排序中经常是针对对象的某个字段排序但是字段为null是处理起来比较麻烦java中有针对此情况的api下面做详细介绍。代码案例TestpublicvoidtestListSort(){ListBookbookListnewArrayList();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的排在最后 */ListBookbookList1bookList.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的排在最前 */ListBookbookList2bookList.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的排在最后 */ListBookbookList3bookList.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的排在最前 */ListBookbookList4bookList.stream().sorted(Comparator.comparing(Book::getPrice,Comparator.nullsFirst(Comparator.reverseOrder()))).collect(Collectors.toList());System.out.println(整体降序price为null的排在最前);System.out.println(bookList4 bookList4);}Book类NoArgsConstructorAllArgsConstructorDatapublicclassBook{privateIntegerprice;privateStringname;}运行结果bookList[Book(pricenull,name水浒传),Book(price9,name钢铁怎样炼成的),Book(pricenull,name百年孤独),Book(price3,name三国演义),Book(price18,name史记)]整理升序price为null的排在最后:bookList1[Book(price3,name三国演义),Book(price9,name钢铁怎样炼成的),Book(price18,name史记),Book(pricenull,name水浒传),Book(pricenull,name百年孤独)]整体升序price为null的排在最前:bookList2[Book(pricenull,name水浒传),Book(pricenull,name百年孤独),Book(price3,name三国演义),Book(price9,name钢铁怎样炼成的),Book(price18,name史记)]整体降序price为null的排在最后:bookList3[Book(price18,name史记),Book(price9,name钢铁怎样炼成的),Book(price3,name三国演义),Book(pricenull,name水浒传),Book(pricenull,name百年孤独)]整体降序price为null的排在最前 bookList4[Book(pricenull,name水浒传),Book(pricenull,name百年孤独),Book(price18,name史记),Book(price9,name钢铁怎样炼成的),Book(price3,name三国演义)]