Java8-使用stream.sorted()对List和Map排序

前提

  java8中,Comparator()是一个函数式接口,可以使用Lambda表达式实现;
  Stream sorted(Comparator<? super T> comparator);

vo

@Data
@AllArgsConstructor
public class DailyDataChartVo {

    /**
     * 日期
     */
    private LocalDate date;

    /**
     * 今日营收
     */
    private BigDecimal revenue;
}

List排序

  1. 按日期排序
List<DailyDataChartVo> list = list.stream()
        .sorted(Comparator.comparing(DailyDataChartVo::getDate))
        .collect(Collectors.toList());
  1. 按日期排序后,逆序
List<DailyDataChartVo> list = list.stream()
        .sorted(Comparator.comparing(DailyDataChartVo::getDate).reversed())
        .collect(Collectors.toList());
  1. 按日期排序后,再按金额排序
List<DailyDataChartVo> list = list.stream()
        .sorted(Comparator.comparing(DailyDataChartVo::getDate)
                .thenComparing(DailyDataChartVo::getRevenue))
        .collect(Collectors.toList());
  1. 按金额排序,排序时过滤Null值(如果排序的字段为null,NPE)
List<DailyDataChartVo> list = list.stream()
        .filter(c -> Objects.nonNull(c.getRevenue()))
        .sorted(Comparator.comparing(DailyDataChartVo::getRevenue))
        .collect(Collectors.toList());
  1. 按金额排序,Null值排在最前面
List<DailyDataChartVo> list = list.stream()
        .sorted(Comparator.comparing(DailyDataChartVo::getRevenue,
                Comparator.nullsFirst(BigDecimal::compareTo)))
        .collect(Collectors.toList());
//注意Comparator.nullsFirst的方法引用中,比较的字段是BigDecimal类型的,如果前后类型不一致,会报错:Non-static method cannot be referenced from a static context
  1. 按金额排序,Null值排在最后面
List<DailyDataChartVo> list = list.stream()
        .sorted(Comparator.comparing(DailyDataChartVo::getRevenue,
                Comparator.nullsLast(BigDecimal::compareTo)))
        .collect(Collectors.toList());

Map排序

  1. 按key排序
Map<LocalDate, BigDecimal> map = map.entrySet()
        .stream()
        .sorted(Map.Entry.comparingByKey())
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (c1, c2) -> c1, LinkedHashMap::new));

  将map转换成流,在流中对元素进行排序,排序后,再用LinkedHashMap收集来保留顺序

public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() {
    return (Comparator<Map.Entry<K, V>> & Serializable)
        (c1, c2) -> c1.getKey().compareTo(c2.getKey());
}

  Map.Entry.comparingByKey():对任意的c1, c2进行比较,然后将结果强制转换成一个可序列化的Comparator<Map.Entry<K, V>>
Collectors.toMap()基础

  1. 按key排序后,逆序
Map<LocalDate, BigDecimal> map = map.entrySet()
        .stream()
        .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (c1, c2) -> c1, LinkedHashMap::new));
  1. 按value排序
Map<LocalDate, BigDecimal> map = map.entrySet()
        .stream()
        .sorted(Map.Entry.comparingByValue())
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (c1, c2) -> c1, LinkedHashMap::new));
posted @ 2020-12-02 21:35  米雷特  阅读(12430)  评论(0编辑  收藏  举报