Dan*_* K. 4 java arraylist deduplication
甲Rec对象具有称为一个成员变量tag这是一个String.
如果我有一个List的RecS,我怎么可能去欺骗基础上,该列表tag的成员变量?
我只需要确保每个值List只包含一个.Rectag
类似下面的内容,但我不确定什么是保持跟踪计数等的最佳算法:
private List<Rec> deDupe(List<Rec> recs) {
for(Rec rec : recs) {
// How to check whether rec.tag exists in another Rec in this List
// and delete any duplicates from the List before returning it to
// the calling method?
}
return recs;
}
Run Code Online (Sandbox Code Playgroud)
暂时存放在HashMap<String,Rec>.
创建一个HashMap<String,Rec>.遍历所有Rec对象.对于每一个,如果tag已经存在作为关键字HashMap,则比较两者并决定保留哪一个.如果没有,那就把它放进去吧.
完成后,该HashMap.values()方法将为您提供所有唯一Rec对象.
试试这个:
private List<Rec> deDupe(List<Rec> recs) {
Set<String> tags = new HashSet<String>();
List<Rec> result = new ArrayList<Rec>();
for(Rec rec : recs) {
if(!tags.contains(rec.tags) {
result.add(rec);
tags.add(rec.tag);
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
这Rec将Set根据标签检查每个标签.如果集合已包含标记,则它是重复的,我们会跳过它.否则,我们将添加Rec到结果中并将标记添加到集合中.
| 归档时间: |
|
| 查看次数: |
8795 次 |
| 最近记录: |