Reputation: 29806
Is it possible in Java to filter a List based on some criteria without iteration? I have a List of size 10000 full of beans where those beans have a property of type boolean. If I want to filter that list based on that boolean property is it necessary to iterate the whole List or there is some other way?
Upvotes: 0
Views: 2868
Reputation: 91
You can do this using stream in Java 8. Assume you have a list of electric and non-electric cars and you want to extract only electric:
List<Car> electricCars= cars.stream().filter(c -> c.isElectric()).collect(Collectors.toList());
Upvotes: 0
Reputation: 54584
You could write a wrapper class that implements the List interface and just "hides" all beans with the said property. However a lot of operations (e.g. every index based function) would be very inefficient, so it depends what exactly you want to do with the "filtered" List.
Upvotes: 1
Reputation: 718798
If you mean, without using an Iterator
, then the answer is Yes. For example:
for (int i = 0; i < list.size(); ) {
MyElement element = list.get(i);
if (element.getMyProperty()) {
list.remove(i);
} else {
i++;
}
}
Depending on the List
implementation, this could be an expensive way of implementing filtering than using an Iterator
and Iterator.remove()
. (For instance, if list is a LinkedList
then list.get(i)
and list.remove(i)
are both O(N)
and hence the list filtering is O(N^2)
. By contrast, filtering the same list with an Iterator
would be O(N)
.)
However, if you are asking if you can filter your list without checking each element in the list, then the answer is No. You'd need some secondary data structure, or the list to be ordered on the property to achieve better than O(N)
filtering.
Upvotes: 1
Reputation: 18998
You've got a list of 10000 things and you want to magically be able to select some of them by some criteria without actually going to each one in turn and seeing if it matches the criteria? Ummm... no. You might be able to find a library which will hide the iteration from you, but ultimately you're going to have to visit each item to see if it matches or not.
Upvotes: 2