0

以下の関数は商品リストを返します。商品リストは一意である必要があります。

ベクター 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;
}
4

2 に答える 2

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());
}
于 2012-06-19T04:06:06.790 に答える
0

ServAttributesクラス、オーバーライドequals、およびメソッドにアクセスできる場合はhashCode、次のコードを使用して重複を削除します。

注: これは の HashSet を返しますServAttributes。製品名だけが必要な場合は、ベクトルを反復処理する必要があります。

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

クラスでは、次のようにandを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;
}
于 2012-06-19T04:31:11.200 に答える