-1

How to remove the elements of array list 1 which are avaliable from array list 2?

for example

ArrayList<AClass> list1 = new ArrayList<AClass>(); //AClass(int IDNumber, String date)
ArrayList<Integer> list2 = new ArrayList<Integer>();

AClass a1 = new AClass(1, "20/01/2013");
AClass a2 = new AClass(2, "21/01/2013");
AClass a3 = new AClass(3, "22/01/2013");
AClass a4 = new AClass(4, "23/01/2013");

list1.add(a1);
list1.add(a2);
list1.add(a3);
list1.add(a4);

list2.add(2);
list2.add(4);

//remove 2 and 4 from list1,

the size of the lists will be big, is there any methods or algorithms to remove them.

Im expecting answer as

// after removing Im expecting answer from list1 as
[1,22/01/2013]
[3,22/01/2013]
vijay
  • 1,129
  • 7
  • 22
  • 34

1 Answers1

2

Use a HashSet<Integer> rather than a List<Integer>, then iterate through list1, and remove every element which has a num contained in the Set<Integer>:

for (Iterator<AClass> it = list1.iterator(); it.hasNext(); ) {
    AClass c = it.next();
    if (set.contains(c.getNum())) {
        it.remove();
    }
}

A HashSet lookup is O(1), whereas a List lookup is O(N).

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 1
    I think the OP's trying to remove elements at index 2 and 4. A HashSet won't let him do that. There are no duplicate values in his example. – ARRG Jul 15 '13 at 21:33
  • 2
    No. He's trying to remove element that have, in their num field, a value that is in a second collection: *"How to remove the elements of array list 1 which are avaliable from array list 2?"*. BTW, there's no index 4 in his example. – JB Nizet Jul 15 '13 at 21:37
  • Actually after re-reading carefully, his example doesn't make sense anyway (doesn't even compile). He uses `add(index, E item)`, which prompted my comment above, but you're right that it's possibly not what he meant. – ARRG Jul 16 '13 at 06:27
  • @ARRG: its not index its an ID number, the list1 has some more column, which I didn't mention, to just show it in simple way. (1,2,3,4) are ID numbers. – vijay Jul 16 '13 at 07:43