//操作类 public class BizAgentAudit { private String supplierOrgId; private int age; private String name; public BizAgentAudit() { super(); } public String getSupplierOrgId() { return supplierOrgId; } public void setSupplierOrgId(String supplierOrgId) { this.supplierOrgId = supplierOrgId; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } } //JDK1.8新特性遍历 //方案1: List<BizAgentAudit> rejectList = new ArrayList<>(); BizAgentAudit temp1 = new BizAgentAudit(); BizAgentAudit temp2 = new BizAgentAudit(); BizAgentAudit temp3 = new BizAgentAudit(); BizAgentAudit temp4 = new BizAgentAudit(); //偷懒,没给对象赋值,你们得赋值哦 rejectList.add(temp1); rejectList.add(temp2); rejectList.add(temp3); rejectList.add(temp4); //去重 rejectList = rejectList.stream() .collect(Collectors.collectingAndThen(Collectors.toCollection(()-> new TreeSet<> (Comparator.comparing(BizAgentAudit::getSupplierOrgId))), ArrayList::new)); //方案2:
List<BizAgentAudit> rejectList = new ArrayList<>(); BizAgentAudit temp1 = new BizAgentAudit(); BizAgentAudit temp2 = new BizAgentAudit(); BizAgentAudit temp3 = new BizAgentAudit(); //偷懒,没给对象赋值,你们得赋值哦 rejectList.add(temp1); rejectList.add(temp2); rejectList.add(temp3); rejectList .stream().filter( distinctByKey(o -> o.getSupplierOrgId()) ).forEach( p ->{ //业务处理操作 } );
//自定义根据对象属性过滤重复的对象 private <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) { Map<Object, Boolean> seen = new ConcurrentHashMap<>(); return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; }