Java哈希集删除重复

时间:2012-06-19 03:52:37

标签: java

以下函数返回产品列表。产品清单应该是唯一的。

向量ServAttributes存储自定义类的对象。自定义类有一个函数getProduct,它提供可能包含重复项的产品名称。

我是否需要滚动整个矢量,检索对象,调用函数getProduction并添加到哈希集以删除重复的产品? Vector有时会存储400个自定义类对象。有没有简短的方法来执行以下功能?

private Vector<ServAttributes> ServAttributes = null;

public HashSet<String> retProduct() {

    HashSet<String> Produset = new HashSet<String>();

    for (int x = 0; x < ServAttributes.size(); x++) {
        ServAttributes record = ServAttributes.get(x);

        if (record.getProduct()) != null) {
            Produset.add(record.getProduct());
        }   

    return Produset;
}

2 个答案:

答案 0 :(得分:1)

使用像Guava这样的通用帮助程序库,您可以以功能方式执行此操作:

return Sets.newHashSet(Iterables.filter(Iterables.transform(serverAttributes, new Function<ServAttributes, String>() {
    public void apply(ServAttributes attributes) {
        return attributes.getProduct();
    }
}), Predicates.notNull()));

使用Java库存,您可以进行一些改进。您可以为首发使用增强型for循环:

for ( ServAttributes attributes : serverAttributes ) {
    productSet.add(attributes.getProduct());
}

答案 1 :(得分:0)

如果您有权使用ServAttributes课程,则可以覆盖equalshashCode方法,然后使用以下代码删除副本:

注意:这会返回ServAttributes的HashSet。如果您只需要产品名称,那么您将不得不遍历矢量。

HashSet<ServAttributes> noDub= new HashSet(new LinkedHashSet(ServAttributes));

ServAttributes班级中,覆盖equalshashCode,如下所示:

@Override
public int hashCode() {
    return product.hashCode();
}
@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if(obj instanceof ServAttributes) {
        ServAttributes s1 = (ServAttributes)obj;

        if(s1.getProduct().equals(this.getProduct())) {
            return true;
        }
    }
    return false;
}
相关问题