Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding duplicate values in arraylist

I have an ArrayList<Car>

For Example

class Car{
   String carName;
   int carType;
}

Now, I have to find if the list has any cars having same name. What is the best way to do this?

like image 423
Makky Avatar asked Sep 02 '11 09:09

Makky


People also ask

Can ArrayList have duplicate values?

ArrayList allows duplicate values while HashSet doesn't allow duplicates values. Ordering : ArrayList maintains the order of the object in which they are inserted while HashSet is an unordered collection and doesn't maintain any order.


2 Answers

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.

like image 119
Swaranga Sarma Avatar answered Oct 12 '22 01:10

Swaranga Sarma


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.

like image 41
Martin Gamulin Avatar answered Oct 12 '22 00:10

Martin Gamulin