Cata
Cata

Reputation: 11211

Java ArrayList filter by element's properties

I have an ArrayList containing Car objects and I want to get from that ArrayList all the unique names as String or just the Car objects that meet that criteria.

EG:

public class Car {

    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }
}

Now I have carArray that contains a lot of Car objects. To get the unique names I am doing something like this:

Set<String> setOfNames = new HashSet<String>();

for (Car car : carArray) {
    setOfNames.add(car.getName());
}

for (String name : setOfNames) {
    System.out.println(name);
}

Is there a better/faster way to filter an ArrayList by its elements properties?

Thank you!

Upvotes: 0

Views: 1658

Answers (3)

Aurelian Cotuna
Aurelian Cotuna

Reputation: 3081

I guess you are talking about some properties like features (available in other languages), but not available in java, so the best approach is to use setters and getters. So my suggestion is to stick with your code since is working pretty fast :)

Good luck, Arkde

Upvotes: 1

Zohaib
Zohaib

Reputation: 7116

Does your set setOfNames contains unique values? Because if this is the implementation of Car class then you have not overridden the methods of equals and hashCode, How does hashSet make sure that two objects are identical ?

I guess, you will have to override the equals and hashcode method to make sure that hashset does not contain duplicates.

Upvotes: 0

Thomas
Thomas

Reputation: 88737

You'd have to iterate over the list anyways, check each entry and collect it into another collection. If you do the same search multiple times sorting the list by that criteria might be an option.

A side note: if carArray is actually a Car[] you don't need the cast inside your first loop, just do for (Car car : carArray). If it is an Object[] you should rethink your design, since in your loop you assume every entry to be a Car anyways.

Upvotes: 1

Related Questions