Extract elements from list based on object property type

Posted by Dustin Digmann on Stack Overflow See other posts from Stack Overflow or by Dustin Digmann
Published on 2010-01-22T00:52:35Z Indexed on 2012/07/03 3:16 UTC
Read the original article Hit count: 171

Filed under:

Often, I have a list of objects. Each object has properties. I want to extract a subset of the list where a specific property has a predefined value.

Example:

I have a list of User objects. A User has a homeTown. I want to extract all users from my list with "Springfield" as their homeTown.

I normally see this accomplished as follows:

List users = getTheUsers();

List returnList = new ArrayList();

for (User user: users) {

   if ("springfield".equalsIgnoreCase(user.getHomeTown()) 

        returnList.add(user); 

}

I am not particularly satisfied with this solution. Yes, it works, but it seems so slow. There must be a non-linear solution.

Suggestions?

© Stack Overflow or respective owner

Related posts about java