I have a List
of objects. I want to iterate through this list of objects and process some subsets of objects based on a condition and finally create a new list of objects with some processed objects being eliminated.
What is the best way to do this.?
Example:
Actual object : List<Cars>
Cars
with same speed.Cars
, the ones which are of same model are to be eliminated.The Google Guava libraries have:
Iterables.filter(cars, new Predicate<Car>() {
@Override
public boolean apply(Car car) {
//return true or false depending on whether you
// want this car to remain in the list
}
}
You can also use an intermediate Set
- i.e.
cars = new ArrayList<Car>(new HashSet<Car>(cars));
where you have properly implemented hashCode
and equals
. This option is viable if this is the identity of your car.
You can also use an iterator:
for (Iterator<Car> it = cars.iterator(); it.hasNext();) {
Car car = it.next();
if (conditions here) {
it.remove();
}
}
By the way, I'm aware that the above examples don't solve your problem completely - you should still consider what to iterate within the outer loops.
If you are looking to do custom equals comparing, then you should define a Comparator<Car>
and then just loop through the Cars.
List<Car> originalList;
Comparator<Car> c = new CarSpeedComparator();
List<Car> result = carFilter(originalList, c);
/// Below is the filter method
public static List<Car> carFilter(List<Car> original, Comparator<Car> comp)
List<Car> result = new ArrayList<Car>();
// Process each car
for (Car car: original) {
boolean containsC = false;
// now we check each car in the result
// to see if we already have an equivalent car
for (int i = 0; i < result.size(); i++) {
// if the two cars are equivalent under the rules
// then we already have that car in the list
if (comp.compare(result.get(i), car) == 0) {
containsC = true;
break;
}
}
// if the result does not contain an equivalent car,
// add it to the list
if (!containsC) result.add(car)
}
return result;
}
//// Implementation of one of the necessary comparators
public class CarSpeedComparator implements Comparator<Car> {
public int compare(Car c1, Car c2) {
return c1.getSpeed() - c2.getSpeed();
}
}
The resulting list will only contain one car of each speed.
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