Finding duplicate values in arraylist

后端 未结 5 710
你的背包
你的背包 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:19

    Try this:

    List cars = getCars();
    Set names = new HashSet();
    for (Car car:cars) {
      if (names.contains(car.getName()) {
        duplicate(car);   // some magic handler
      } else {
        names.add(car.getName());
      }
    }
    

    Note: this will give you the car names that are duplicate. A follow on would be extracting all cars with those names from the list (if you need the Car objects)

提交回复
热议问题