项目实战中可以用stream流的分组和排序来自定义排序和分组
@Data
@AllArgsConstructor
class Jiaoyi {
private BigDecimal jy;
private String name;
private LocalDateTime date;
}
/**
* 分组
*/
@Test
public void test3() {
List<Jiaoyi> list = new ArrayList<>();
list.add(new Jiaoyi(new BigDecimal(1), "张三", LocalDateTime.of(LocalDate.now(), LocalTime.MAX)));
list.add(new Jiaoyi(new BigDecimal(1), "张三", LocalDateTime.now()));
list.add(new Jiaoyi(new BigDecimal(1000.3333), "李四", LocalDateTime.now()));
list.add(new Jiaoyi(new BigDecimal(4.55), "李四", LocalDateTime.now()));
list.add(new Jiaoyi(new BigDecimal(8.55), "张三", LocalDateTime.now()));
list.add(new Jiaoyi(new BigDecimal(1), "李四", LocalDateTime.now()));
//判断是否为null
Map<LocalDateTime, List<Jiaoyi>> collect = Optional.ofNullable(list)
//不为null返回该流
.map(List::stream)
//为null返回默认的null
.orElseGet(Stream::empty)
//根据时间分组
.collect(Collectors.groupingBy(s -> s.getDate()));
System.out.println(JSON.toJSONString(collect, true));
}
/**
* 排序
*/
@Test
public void test4() {
List<Jiaoyi> list = new ArrayList<>();
list.add(new Jiaoyi(new BigDecimal(1), "张三", LocalDateTime.of(LocalDate.now(), LocalTime.MAX)));
list.add(new Jiaoyi(new BigDecimal(1), "张三", LocalDateTime.now()));
list.add(new Jiaoyi(new BigDecimal(1000.3333), "李四", LocalDateTime.now()));
list.add(new Jiaoyi(new BigDecimal(4.55), "李四", LocalDateTime.now()));
list.add(new Jiaoyi(new BigDecimal(8.55), "张三", LocalDateTime.now()));
list.add(new Jiaoyi(new BigDecimal(1), "李四", LocalDateTime.now()));
List<Jiaoyi> listJiaoyi = list.stream()
.sorted(Comparator
//根据价格排序
.comparing(Jiaoyi::getJy, Comparator.reverseOrder())
//如果有几个价格相同那么这几个根据时间排序
.thenComparing(Jiaoyi::getDate)
//如果有几个价格相同以及这几个时间一致那么根据名称排序
.thenComparing(Jiaoyi::getJy, (a, b) -> {
if (Objects.equals("张三",a)) {
return 1;
} else {
return 0;
}
})).collect(Collectors.toList());
System.out.println(JSON.toJSONString(listJiaoyi, true));
}
上面的Optional用法
/**
* 三中创建optional的方式
*/
@Test
public void test1(){
//创建空optional对象
Optional.empty();
//使用非null值创建optional对象
Optional.of("你好");
//使用任意值创建optional对象
Optional<String> op = Optional.ofNullable(null);
//使用optional 的时候避免使用这个方法
op.isPresent();
//optional 引用缺失给一个默认值
System.out.println(op.orElse("你好啊"));
//optional 自定义引用缺失
System.out.println( op.orElseGet(() ->{
return "失去";
}));
//引用缺失抛出异常
// op.orElseThrow(() -> {
// throw new RuntimeException("失去");
// });
//optional不为null则返回true
op.ifPresent(System.out::println);
}
/**
* 测试
* @param list
*/
public static void stream(List<String> list){
list.stream().forEach(System.out::println);
}
public static void stream2(List<String> list){
//如果不是null
Optional.ofNullable(list)
//则构建该list流
.map(List::stream)
//如果是 那就自定义引用缺失设置null流
.orElseGet(Stream::empty)
.forEach(System.out::println);
}
public static void main(String[] args) {
//输入null会报错
// stream(null);
//输入null不会报错,防止null异常
stream2(null);
}