There code is by far not identical; specifically Collectors.toMap
says that it will return a Map
:
There are no guarantees on the type, mutability, serializability, or thread-safety of the Map returned.
There are absolutely no guarantees what-so-ever that the returned Map
is actually a HashMap
. It could be anything other - any other Map
here; so assigning it to a HashMap
is just wrong.
Then there is the way you build the Collector
. It could be simplified to:
customerList.stream().collect(Collectors.toMap(Customer::getId, Function.identity()));
The method reference Customer::getId
, as opposed to the lambda expression, will create one less method (since lambda expressions are de-sugared to methods and method references are not).
Also Function.identity()
instead of t -> t
will create less objects if used in multiple places. Read this.
Then there is the fact how a HashMap
works internally. If you don't specify a default size
, it might have to re-size - which is an expensive operation. By default Collectors.toMap
will start with a default Map
of 16 entries and a load_factor
of 0.75
- which means you can put 12 entries into it before the next resize.
You can't omit that using Collectors.toMap
since the supplier of that will always start from HashMap::new
- using the default 16 entries and load_factor of 0.75.
Knowing this, you can drop the stream entirely:
Map<String, Customer> map = new HashMap<String, Customer>((int)Math.ceil(customerList.size() / 0.75));
customerList.forEach(x -> map.put(x.getId(), x));