ptpdlc
ptpdlc

Reputation: 2621

Collectors.toMap with Supplier argument

I cannot understand, nor find a suitable example of the Collectors.toMap method with the Supplied argument; this one.

I fully understand the others, with functions to create the keys, the values, the binary thing to handle duplicates, I just don't understand that last method that has an extra supplier argument.

Upvotes: 2

Views: 2612

Answers (2)

Suren Aznauryan
Suren Aznauryan

Reputation: 1094

The method you mentioned lets you to decide both:

  • the concrete map implementation (e.g. HashMap , ConcurrentHasMap, etc.. )
  • concrete instance of that implementation (you can pass either newly created instance or some instance that is created far ago on the heap of your app)

In contrast to this method, in other 2 overloaded versions the implementation of map will be chosen by library and a new instance of it will be created.

Upvotes: 2

Harmlezz
Harmlezz

Reputation: 8078

Here is an example:

Arrays.asList(1, 2, 3).stream()
      .collect(Collectors.toMap(i -> i, i -> i, (i, j) -> i, HashMap::new));

In this example Supplier<M> mapSupplier is HashMap::new, a factory capable of creating an empty Map.

Upvotes: 5

Related Questions