stream() 进行分组 排序以及Optional转换
每篇一句励志:天时不如地利,地利不如人和。
- stream()分组、排序
Set<Map.Entry<String, Optional<Company>>> entries = resultList.stream().
filter(t -> StringUtils.isNotBlank(t.getExamineId())).
collect(Collectors.groupingBy(Company::getAppId, Collectors.maxBy(Comparator.comparing(Company::getExamineTime)))).entrySet();
我是返回Set集合,还可以返回Map(把.entrySet()去除即可),根据自己需求而定。
- Optional转换List
List<Company> examine = entry.getValue().map(Collections::singletonList).orElse(Collections.emptyList());
据说还有这样写的,可以 try 一 try
import static java.util.stream.Collectors.*;
//转为List
List<String> list = collect(opt, toList());
//转为Set
Set<String> set = collect(opt, toSet());