Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating and processing an ArrayList

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>

  1. Iterate through this list and find Cars with same speed.
  2. In that smaller set of Cars, the ones which are of same model are to be eliminated.
  3. Finally after elimination I get the new list.
like image 650
Magggi Avatar asked Dec 21 '22 23:12

Magggi


2 Answers

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.

like image 132
Bozho Avatar answered Dec 29 '22 06:12

Bozho


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.

like image 35
jjnguy Avatar answered Dec 29 '22 08:12

jjnguy