我通过对我控制之外的服务方法的多次调用在HashSet
中积累了唯一的对象,该方法返回一个List<Record>
。
一个额外的要求是,如果在此过程中发现任何重复,我需要生成一封电子邮件。我可以自己检查重复项,并保留一个可以插入或跳过的List<Record>
,但这样我就不会使用从外部列表自动执行此操作的Set
。显然,在设置添加失败时没有try/catch
,但是有没有更好的方法呢?
HashSet<Record> set = new HashSet<Record>();
for (String org: orgs) {
// External service call
List<Record> result = service.getRecords(org);
// Add All to Set (also need to detect duplicates with resulting logic)
set.addAll(result);
}
发布于 2018-10-30 06:24:52
这取决于结果本身是否可以包含重复的记录,是否可以独立处理第三次出现的记录。
Set<Record> set = new HashSet<>();
for (String org: orgs) {
// External service call
List<Record> result = service.getRecords(org);
// Add All to Set (also need to detect duplicates with resulting logic)
for (Record record: result) {
if (!set.add(record)) {
// Handle duplicate by individual record:
...
}
}
}
或者:
Set<Record> set = new HashSet<>();
Set<Record> duplicates = new HashSet<>();
for (String org: orgs) {
// External service call
List<Record> result = service.getRecords(org);
// Add All to Set (also need to detect duplicates with resulting logic)
Set<Record> duplicateResult = new .HashSet<>(result);
duplicateResult.retainAll(set);
duplicates.addAll(duplicateResult);
set.addAll(result);
}
for (Record record: duplicates) {
// Handle duplicate once:
...
}
https://stackoverflow.com/questions/53054407
复制相似问题