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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With