Finding duplicate values in arraylist

Solution 1:

Create a comparator:

public class CarComparator implements Comparator<Car>
{
    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<Car> duplicates = new ArrayList<Car>();
Set<Car> carSet = new TreeSet<Car>(new CarComparator());
for(Car c : originalCarList)
{
    if(!carSet.add(c))
    {
        duplicates.add(c);
    }
}

Finally in your duplicates you will have all the duplicates.

Solution 2:

If you have

class Car{
   String carName;
   int carType;
}

and

List<Car> list;

that contains a list of cars, then you could have a method like

public static boolean hasDuplicates(List<Car> p_cars) {
    final List<String> usedNames = new ArrayList<String>();
    for (Car car : p_cars) {
        final String name = car.carName;

        if (usedNames.contains(name)) {
            return true;
        }

        usedNames.add(name);
    }

    return false;
}

to find out whether the list of cars have cars with duplicate names.