我有一个List集合,其中每个指标包含一些特性,如重复:metricName,命名空间,车队,类型,组件,firstSeenTime,lastSeenTime等有此列表中重复这样的除了firstSeenTime和lastSeenTime之外,所有属性都是相同的。我正在寻找一种优雅的方式来过滤这个列表,并且只有在存在这样的重复时才返回带有最近lastSeenTime的度量标准。删除基于几个对象属性从列表
东西比这更好:
private List<Metric> processResults(List<Metric metrics) {
List<Metric> results = new ArrayList<>();
for (Metric incomingMetric: metrics) {
// We need to implement "contains" below so that only properties
// other than the two dates are checked.
if (results.contains(incomingMetric) {
int index = results.indexOf(incomingMetric);
Metric existing = results.get(index);
if (incomingMetric.getLastSeen().after(existing.getLastSeen())) {
results.set(index, metricName);
} else {
// do nothing, metric in results is already the latest
}
} else {
// add incomingMetric to results for the first time
results.add(incomingMetric);
}
}
return results;
}
的results.contains检查通过结果遍历所有的指标,如果每个对象除了两个日期的属性相匹配检查完成。
这可能是一个更好的方法,这两种优雅和性能?
感谢。这看起来不错,我使用一个静态嵌套类来构造关键字(在将键构造为字符串时不必处理字段分隔符),但是只是一个字符串就足够了。 – gansvv