业务需求:
我这接到的需求是对一个List进行多条件的去重操作,这个List的泛型是一个User的实体类对象
具体代码:
public ApiResponses<Map<String, Object>> selectDetailByDate(
@RequestBody Map<String, Object> map) {
Map<String, Object> resultMap = new HashMap<>();
List<User> upcList = userService.selectHistory(map);
upcList = upcList.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(User::getImageUrl).thenComparing(User::getUserTime))), ArrayList::new));
resultMap.put("upcList", upcList);
return ApiResponses.success(response, resultMap);
}
解释:
List<User> upcList = userService.selectHistory(map);
这行代码呢,就是通过条件查询到的List,下边的代码则是对List集合进行去重的操作
upcList = upcList.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(User::getImageUrl).thenComparing(User::getUserTime))), ArrayList::new));
首先我们利用java8新特性中的stream流对集合进行操作,collectingAndThen用于对流中的数据进行处理,可以对流中的数据进行聚合操作,接着需要使用toCollection收集器并提供特定集合实现,然后将结果集放到TreeSet中,由于TreeSet的特性是不重复,于是就可以达到去重的效果,Comparator.comparing括号中是筛选的条件,thenComparing方法是拼接第二个筛选条件,最后将流中的元素累积到汇总到 collect 收集器中,再以ArrayList的形式返回。
自己想用上述方法的话,只需要改几个地方就可以,第一个把upcList改成自己要操作的list , 第二就是(User::getImageUrl)将括号中的实体类和获取属性的方法改成自己对应的,如果想单条件去重的话,就删掉 .thenComparing(User::getUserTime)
这段代码就可以了
这种利用java8新特性stream流对集合的操作,远远比自己写的循环判断来的简单有效