我有一個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