1、去重工具类
public class StreamtUtil {
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
}
2.去重并赋值
// 从数据库中查询出的对象集合
List<HR> hrList= hRMapper.selectJoinByExample(example);
// 判端是否为空
if (CollectionUtils.isNotEmpty(hrList)) {
// 进行去重拆解封装
List<StaffVO> staffs= hrList.stream()
.filter(StreamUtil.distinctByKey(HR::getStationId)
.map(hr-> {
StaffVO staffVO = new StaffVO ();
staffVO.setId(hr.getStationId());
staffVO.setName(hr.getStationName());
return staffVO;
}).collect(Collectors.toList());
}
3.获取对象关联id(字符串拼接一对多)去重转integer
// 从数据库中查询出的对象集合
List<HR> hrList= hRMapper.selectJoinByExample(example);
// 判端是否为空
if (CollectionUtils.isNotEmpty(hrList)) {
// 将客户pid拼接成字符串("1,2","3","2,5,6","1,3")
String pidStr = hrList.stream().map(HR::getPid()).collect(Collectors.joining(",");
// 进行去重转换
List<Integer> staffs= Arrays.asList(pidStr.split(",")).stream()
.map(s-> Integer.valueOf(s.trim())).collect(Collectors.toList());
}
4.将对象中的两个字段转为map
List<User> list = new ArrayList<>();
Map<Integer, String> map = list.stream().collect(Collectors.toMap(User::getId, User::getType));
5.集合排序
List<OfficeDetail> detailList = queryList.stream().sorted(Comparator.comparing(OfficeDetail::getEndDate, Comparator.nullsLast(Long::compareTo)). thenComparing(OfficeDetail::getStartDate, Comparator.reverseOrder())).collect(Collectors.toList());
from tq_office
where groupID = #{groupID} and type = #{type} and status = 1 and action != 2 order by IF(endDate=0,99990101 ,endDate ) ASC ,startDate desc