user219882
user219882

Reputation: 15844

Which is the best way to filter List?

Let's say I have this simple class structure:

Vehicle
|-- Bus
`-- Car

Bus and Car extends Vehicle

I have List<Vehicle>. How can I get only buses or cars? I would like to avoid instanceof operator. Do I have to use Visitor pattern or is there any simpler solution?

Upvotes: 0

Views: 250

Answers (3)

Zernike
Zernike

Reputation: 1766

If you don't want instanceOf add field to Vehicle that determine class.

Upvotes: -2

Jon Skeet
Jon Skeet

Reputation: 1503944

Well something will need to use instanceof or an equivalent (such as Class.isInstance).

Guava has a method which does exactly this though: Iterables.filter. So you could use:

List<Bus> buses = Lists.newArrayList(Iterables.filter(vehicles, Bus.class));

Upvotes: 3

solendil
solendil

Reputation: 8458

I see no way to avoid the use of instanceof operator in your case, nor can I see a way to produce much simpler code than this (without help from Guava) :

List<Bus> buses = new ArrayList<Bus>();
for (Vehicle v : vehicles)
    if (v instanceof Bus)
        buses.add(v);

Upvotes: 3

Related Questions