如何删除对象列表?

一个
Rec
对象有一个名为
tag
的成员变量,它是一个
String
。 如果我有
List
Rec
s,我怎么能根据
tag
成员变量来删除列表? 我只需要确保
List
只包含一个
Rec
,每个
tag
值。 类似下面的内容,但我不确定什么是保持跟踪计数等的最佳算法:
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;

}
    
已邀请:
暂时存放在
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;
}
这将检查每个
Rec
Set
标签。如果集合已包含标记,则它是重复的,我们会跳过它。否则,我们将
Rec
添加到结果中并将标记添加到集合中。     
如果
Rec
基于其
tag
值为
.equals
,则变得更容易。然后你可以这样写:
private List<Rec> deDupe( List<Rec> recs )
{
    List<Rec> retList = new ArrayList<Rec>( recs.size() );
    for ( Rec rec : recs )
    {
        if (!retList.contains(rec))
        {
            retList.add(rec);
        }
    }
    return retList;
 }
    
我会用谷歌收藏品做到这一点。您可以使用过滤器函数,使用记住以前标记的谓词,并过滤出之前已存在的标记的Rec。 像这样的东西:
private Iterable<Rec> deDupe(List<Rec> recs) 
{
    Predicate<Rec> filterDuplicatesByTagPredicate = new FilterDuplicatesByTagPredicate();
    return Iterables.filter(recs, filterDuplicatesByTagPredicate);
}

private static class FilterDuplicatesByTagPredicate implements Predicate<Rec>
{
    private Set<String> existingTags = Sets.newHashSet();

    @Override
    public boolean apply(Rec input)
    {
        String tag = input.getTag();
        return existingTags.add(tag);
    }
}
我略微改变了返回Iterable而不是List的方法,但是如果这很重要的话你可以改变它。     
如果你不关心乱码数据(即你有一小部分小对象),你可以这样做:
private List<T> deDupe(List<T> thisListHasDupes){
    Set<T> tempSet = new HashSet<T>();
    for(T t:thisListHasDupes){
        tempSet.add(t);
    }
    List<T> deDupedList = new ArrayList<T>();
    deDupedList.addAll(tempSet);
    return deDupedList;
}
请记住,Set的implmenations将需要一个一致且有效的equals运算符。因此,如果您有自定义对象,请确保已完成。     

要回复问题请先登录注册