lambda 根据属性去重_jdk1.8 lambda表达式过滤重复的对象

//操作类

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 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 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 Predicate distinctByKey(Function super T, Object> keyExtractor) {

Map seen = new ConcurrentHashMap<>();

return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;

}

你可能感兴趣的:(lambda,根据属性去重)