简体   繁体   中英

Find a single object in a collection, HashMap vs List filter

I generate a list of Customer from a file that I read. I store these customers in a HashMap where the key is a unique id :

Map<String, Customer> customers = readCustomers(); //For each object created customers.put(c.getCustomerId(), c);

From a second file I get data that I use to update the object in the HashMap . I use the key in order to find the object to update:

//get the details informations customers.get(customerId).setDetails(details);

In java 8 I could use :

class Customer{
    ... 

    public static Customer find(List<Customer> customers, int id) {
        return customers.stream().filter(c -> c.customerId == id).findAny().get();
    }
}

//usage
List<Customer> customers = readCustomers();    
...
Customer.find(customers, 21).setDetails(details);

would there be a performance improvement by using the Java 8 method ? What is the best practice between these methods?

Searching for a value by key in a HashMap takes O(1) expected time, which is faster than the O(n) that searching for the same value in a List would take.

Using Java 8 Streams doesn't change that, since behind the scenes of the fancy new syntax, it still iterates over the elements of the List until finding a match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM