Imagine I have a class named Car and a bunch of subclasses that extend car like BMW,FORD,etc. So I have this ArrayList of cars and i am trying to separate each object in this ArrayList to diferent ArrayLists, one for each brand. I heard that using instance of is not a good practice so I have no idea how to do this.
I don't really know how to solve this polymorphism use, but i propose to not use instanceof
and use a Map
instead, with the class of the car and the list of the cars as arguments.
In this case, the code should look something like :
private static Collection<List<Car>> separateCars(List<Car> cars) {
Map<Class, List<Car>> result = new HashMap<>(); // creating the empty map with results
for (Car car : cars) { // iterating over all cars in the given list
if (result.containsKey(car.getClass())) { // if we have such car type in our results map
result.get(car.getClass()).add(car); // just getting the corresponding list and adding that car in it
} else { // if we faced with the class of the car that we don't have in the map yet
List<Car> newList = new ArrayList<>(); // creating a new list for such cars
newList.add(car); // adding this car to such list
result.put(car.getClass(), newList); // creating an entry in results map with car's class and the list we just created
}
}
return result.values(); // returning only the lists we created as we don't need car's classes
}
Hope that will help you.
Java 8 Collectors grouping by can be useful in above case
https://www.mkyong.com/java8/java-8-collectors-groupingby-and-mapping-example/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.