0

いくつかのオブジェクトが保存されているリストがあります。特定の属性が存在しないオブジェクトをリストから削除したいと思います。私のサンプル コードは、ここで助けてください。

public class Mysamples {

    private void example() {
        List<SomeType> listWithDuplicates = new ArrayList<SomeType>();

        SomeType someObject1 = new SomeType("hello", "1");
        SomeType someObject2 = new SomeType("hello", "2");
 }

private void removeDuplicates(List<SomeType> listWithDuplicates) {
    /* Set of all attributes seen so far */
    Set<String> attributes = new HashSet<String>();
    /* All confirmed duplicates go in here */
    List duplicates = new ArrayList<SomeType>();

    for (SomeType x : listWithDuplicates) {
        if (attributes.contains(x.getName())) 
        {
            duplicates.add(x);
        }
        attributes.add(x.getName());
    }

    System.out.println(duplicates);
   // System.out.println(attributes);
}

public static void main(String[] args) {
    // TODO code application logic here
    List<SomeType> listWithDuplicates = new ArrayList<SomeType>();
    SomeType someObject1 = new SomeType("hello", "1");
    SomeType someObject2 = new SomeType("hello", "2");
    SomeType someObject3 = new SomeType("hello", "1");
    SomeType someObject4 = new SomeType("hello1", "2");
    SomeType someObject5 = new SomeType("hello1", "1");
    SomeType someObject6 = new SomeType("hello2", "2");


    listWithDuplicates.add(someObject1);
    listWithDuplicates.add(someObject2);
    listWithDuplicates.add(someObject3);
    listWithDuplicates.add(someObject4);
    listWithDuplicates.add(someObject5);
    listWithDuplicates.add(someObject6);
    Mysamples s = new Mysamples();

    s.removeDuplicates(listWithDuplicates);
}
}

アウトプットは

[SomeType{name=hello, id=2}, SomeType{name=hello, id=1}, SomeType{name=hello1, id=1}]

しかし、私は次のように出力したい

[SomeType{name=hello, id=1,SomeType{name=hello, id=2}, SomeType{name=hello, id=1}} SomeType{name=hello1, id=2},SomeType{name=hello1, id=1}]]
4

4 に答える 4

0
private void removeDuplicates(List<SomeType> listWithDuplicates) {
    Map<String, Integer> nameCountMap = new HashMap<String, Integer>();
    // get count of each name
    for (SomeType x : listWithDuplicates) {
        Integer count = nameCountMap.get(x.getName());
        if (count == null) {
            count = new Integer(0);
        }
        count++;
        nameCountMap.put(x.getName(), count);
    }
    // Print duplicates
    for (SomeType x : listWithDuplicates) {
        if (nameCountMap.get(x.getName()) > 1) {
            System.out.println(x);
        }
    }
}
于 2013-11-11T11:11:22.260 に答える
0

あなたのアルゴリズムは、最初に名前に遭遇した後にのみ重複を見つけます。したがって、たとえば、最初の「hello」は属性セットにないため、それを追加すると (ただし、重複とは見なされません)、次の 2 つの「hello」エントリが重複と見なされ、重複リストに追加されます。「hello1」も同様です。最初に検出されたものを含め、すべての重複を見つけたい場合は、コレクションに対して 2 つのパスを実行する必要があります。最初に属性セット内のすべての名前を収集し、次にすべての重複にフラグを立てます。

于 2013-11-11T05:07:38.993 に答える