记录java常用方法
1.取两个集合的差集
java
public class StreamApiTest {
public static void main(String[] args) {
List<MktCamCustDetail> batchPos = Arrays.asList(
new MktCamCustDetail("123456", 123456L, "张三"),
new MktCamCustDetail("345678", 345678L, "王五"),
new MktCamCustDetail("234567", 234567L, "赵六"),
new MktCamCustDetail("123456", 123456L, "张三"));
// 从 batchPos 中提取 objId 列表,去重后直接用于查询
List<MktCamCustDetail> mktCamCustDetailList = Optional.ofNullable(batchPos)
.orElse(Collections.emptyList()) // 防止 batchPos 为 null
.stream()
.map(MktCamCustDetail::getObjId)
.filter(Objects::nonNull) // 避免包含 null 的 objId
.distinct()
.collect(Collectors.collectingAndThen(Collectors.toList(), StreamApiTest::getMktCamCustDetails));
// 取读取到的数据与数据库中已存在的资产的差集,即新增的资产
List<MktCamCustDetail> newMktCamCustDetailList = batchPos.stream()
.filter(m -> mktCamCustDetailList.stream().noneMatch(m2 -> m2.getObjId().equals(m.getObjId())))
.collect(Collectors.toList());
System.out.println(newMktCamCustDetailList);
}
/**
* 根据 objIdList 查询 MktCamCustDetail 列表
*
* @param objIdList
* @return
*/
public static List<MktCamCustDetail> getMktCamCustDetails(List<String> objIdList) {
List<MktCamCustDetail> list = Arrays.asList(
new MktCamCustDetail("123456", 123456L, "张三"),
new MktCamCustDetail("345678", 345678L, "王五"),
// new MktCamCustDetail("234567", 234567L, "赵六"),
new MktCamCustDetail("123456", 123456L, "张三")
);
// 如果 objIdList 为空,直接返回空列表,避免不必要的查询
return list;
}
}
/**
* MktCamCustDetail 实体类
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
class MktCamCustDetail {
private String objId;
private Long custId;
private String custName;
}