Extract items from a list based on an object type

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

Example:

I have a list of User objects. User has homeTown. I want to extract all users from my list using Springfield as homeTown.

Usually I see that this is done as follows:

User List = getTheUsers ();

List returnList = new ArrayList ();

for (User User: Users) {

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

        returnList.add(user); 

}

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

Suggestions?

+3
source share
5 answers

Predicates. .

, (< 100 ) . (5k-10k) 20-30%. , , . , , , foreach.

0

, , - , , , . , .

. , Groovy each() . - ...

def returnList = new ArrayList();
users.each() {
    if ("springfield".equalsIgnoreCase(it.getHomeTown()) 
        returnList.add(user); 
};
+1

. , List .

List Map , . , , .

List findAllBy(String propertyName, String propertyValue);, - .

. , , "user.address.city". .

, 1000 List, , , .

+1

, , . , FindAll - . , , . , HashTables, Dictionaries DataTables, . , Java-, , , .

0

, . , .

( ), TreeMap ( HashMap) homeTown , , Map ( , , ). , .

In case you need a list of all users with a given homeTown, you just need to find this list on the Map and return it (without copying the necessary elements), I'm not 100% sure about the implementation of Map in Java, but the full method should be constant time (worst-case logarithmic, depending on map implementation).

0
source

Source: https://habr.com/ru/post/1729493/


All Articles