0

arraylist から一意のオブジェクトをフィルタリングするにはどうすればよいですか。

List<LabelValue> uniqueCityListBasedState = new ArrayList<LabelValue>();
for (LabelValue city : cityListBasedState) {
    if (!uniqueCityListBasedState.contains(city)) {
        uniqueCityListBasedState.add(city);
    }
}

これは私のコードです。しかし、問題は、オブジェクトではなく、そのオブジェクト内のプロパティの値でフィルタリングする必要があることです。この場合、名前を持つオブジェクトを除外する必要があります。

あれはcity.getName()

4

4 に答える 4

6
List<LabelValue> uniqueCityListBasedState = new ArrayList<LabelValue>();
        uniqueCityListBasedState.add(cityListBasedState.get(0));
        for (LabelValue city : cityListBasedState) {
            boolean flag = false;
            for (LabelValue cityUnique : uniqueCityListBasedState) {    
                if (cityUnique.getName().equals(city.getName())) {
                    flag = true;                    
                }
            }
            if(!flag)
                uniqueCityListBasedState.add(city);

        }
于 2013-03-08T07:44:20.633 に答える
2

設定するリストを変更できると仮定します。

代わりにセット コレクションを使用してください。

セットは、重複する要素を含むことができないコレクションです。

于 2013-03-08T06:20:56.543 に答える
2

equals()のandhashCode()メソッドを上書きしますLabelValue(hashCodeこの場合は必須ではありません):

String name;

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    LabelValueother = (LabelValue) obj;
    if (name == null) {
        if (other.name != null)
            return false;
    } else if (!name.equals(other.name))
        return false;
    return true;
}
于 2013-03-08T06:57:25.763 に答える
1

これを解決する1つの方法があります。

equals()メソッドとhashCode()LabelValueをオーバーライドする必要があります。

equals()メソッドはnameプロパティを使用する必要があり、メソッドも使用する必要がありhashCode()ます。

その後、コードが機能します。

PS。あなたの LabelValue オブジェクトは name プロパティだけで区別できると仮定しています。これは、質問に基づいてとにかく必要と思われるものです。

于 2013-03-08T06:15:42.740 に答える