Finding duplicate values in arraylist

后端 未结 5 698
你的背包
你的背包 2020-11-28 06:41

I have an ArrayList

For Example

class Car{
   String carName;
   int carType;
}

Now, I have to find if the

5条回答
  •  北海茫月
    2020-11-28 07:23

    Create a comparator:

    public class CarComparator implements Comparator
    {
        public int compare(Car c1, Car c2)
        {
            return c1.carName.compareTo(c2.carName);
        }
    }
    

    Now add all the cars of the ArrayList to a SortedSet, preferably TreeSet; if there are duplicates add to the list of duplicates:

    List duplicates = new ArrayList();
    Set carSet = new TreeSet(new CarComparator());
    for(Car c : originalCarList)
    {
        if(!carSet.add(c))
        {
            duplicates.add(c);
        }
    }
    

    Finally in your duplicates you will have all the duplicates.

提交回复
热议问题