Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 271
Loci Avatar asked May 15 '15 13:05

Loci


People also ask

Which is faster HashMap or list?

While the HashMap will be slower at first and take more memory, it will be faster for large values of n. The reason the ArrayList has O(n) performance is that every item must be checked for every insertion to make sure it is not already in the list.

How will you run a filter on a collection?

You can filter Java Collections like List, Set or Map in Java 8 by using the filter() method of the Stream class. You first need to obtain a stream from Collection by calling stream() method and then you can use the filter() method, which takes a Predicate as the only argument.

Can we store objects in HashMap and how do you retrieve them?

In the ArrayList chapter, you learned that Arrays store items as an ordered collection, and you have to access them with an index number ( int type). A HashMap however, store items in "key/value" pairs, and you can access them by an index of another type (e.g. a String ).

How do you filter a list of objects using a stream?

Java stream provides a method filter() to filter stream elements on the basis of given predicate. Suppose you want to get only even elements of your list then you can do this easily with the help of filter method. This method takes predicate as an argument and returns a stream of consisting of resulted elements.


1 Answers

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.

like image 195
Eran Avatar answered Oct 25 '22 09:10

Eran