场景
- 对list去重本来使用set转换下是快速的方式,但是需要重新class的equals和hashCode,equals根据需要对比的数据重新一遍就行了,但是equals需要保证相同的特定属性得到相同的值,实现的方式简单 但是需要考虑效率 。这个效率拿不准就需要一个新的去重方式了
实现
- Collectors.collectingAndThen在进行归纳动作结束之后,对归纳的结果进行二次处理。
templateList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(item->item.getShopId() + item.getKid()))), ArrayList::new));
- 举例
List<TradeExternalAuthTemplate> templateList = new ArrayList<>();
TradeExternalAuthTemplate template = new TradeExternalAuthTemplate();
template.setShopId(1);
template.setKid("kid1");
template.setAuth("auth");
templateList.add(template);
TradeExternalAuthTemplate template2 = new TradeExternalAuthTemplate();
template2.setShopId(1);
template2.setKid("kid1");
template2.setAuth("auth2");
templateList.add(template2);
List<TradeExternalAuthTemplate> tradeFilterList = templateList.stream().distinct().collect(Collectors.toList());
List<TradeExternalAuthTemplate> tradeFilterList2 = templateList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(item -> item.getShopId()+ item.getKid()))), ArrayList::new));
System.out.println(tradeFilterList);
System.out.println(tradeFilterList2);