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(Comparatorparing(DailyDataChartVo::getDate))
.List());
2. 按⽇期排序后,逆序
List<DailyDataChartVo> list = list.stream()
.sorted(Comparatorparing(DailyDataChartVo::getDate).reversed())
.List());
3. 按⽇期排序后,再按⾦额排序
List<DailyDataChartVo> list = list.stream()
.sorted(Comparatorparing(DailyDataChartVo::getDate)
.thenComparing(DailyDataChartVo::getRevenue))
.List());
4. 按⾦额排序,排序时过滤Null值(如果排序的字段为null,NPE)
List<DailyDataChartVo> list = list.stream()
.
filter(c -> Revenue()))
.sorted(Comparatorparing(DailyDataChartVo::getRevenue))
.List());
5. 按⾦额排序,Null值排在最前⾯
List<DailyDataChartVo> list = list.stream()
.sorted(Comparatorparing(DailyDataChartVo::getRevenue,
Comparator.nullsFirst(BigDecimal::compareTo)))
.List());
//注意Comparator.nullsFirst的⽅法引⽤中,⽐较的字段是BigDecimal类型的,如果前后类型不⼀致,会报错:Non-static method cannot be referenced from a static context
6. 按⾦额排序,Null值排在最后⾯
List<DailyDataChartVo> list = list.stream()
java stream.sorted(Comparatorparing(DailyDataChartVo::getRevenue,
Comparator.nullsLast(BigDecimal::compareTo)))
.List());
Map排序
1. 按key排序
Map<LocalDate, BigDecimal> map = Set()
.stream()
.sorted(Map.EntryparingByKey())
.Map(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()Key());
}
  Map.EntryparingByKey():对任意的c1, c2进⾏⽐较,然后将结果强制转换成⼀个可序列化的Comparator<Map.Entry<K, V>>
2. 按key排序后,逆序
Map<LocalDate, BigDecimal> map = Set()
.stream()
.sorted(Map.verseOrder()))
.Map(Map.Entry::getKey, Map.Entry::getValue, (c1, c2) -> c1, LinkedHashMap::n
ew));
3. 按value排序
Map<LocalDate, BigDecimal> map = Set()
.stream()
.sorted(Map.EntryparingByValue())
.Map(Map.Entry::getKey, Map.Entry::getValue, (c1, c2) -> c1, LinkedHashMap::new));

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。