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?
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.
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.
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 ).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With