-5

I have an ArrayList whose each element is of type DataType, where DataType is a class:

class DataType{
 String dId;
 String dType;
 String rId;
}

I need to remove all such elements from the list whose rId is equal to any other element's dID. i.e. if DataType D1 has value of dID as "abc" and DataType D2 has value of rID as "abc", than remove both D1 and D2 from the list.

Could someone please suggest the most appropriate approach for doing this.

user2971387
  • 109
  • 1
  • 3
  • 11

1 Answers1

4

The easiest would be to traverse the list once and create a HashMap<String, List<DataType>>. You will map every object to their dID which forms the primary key.

After that you can iterate over your ArrayList, check the rId of the current object and see if it's in the HashMap. HashMap has O(1) lookup time so this should be a non issue. If the value is present, remove the current value (you're using an Iterator to prevent a ConcurrentModificationException) and remove the objects inside the value-part of the key-value pair as well.

Make sure you have correctly implemented .equals(Object o) and .hashcode().

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170