What’s the difference between

Toshiya Komoda
Jun 22, 2021

--

It’s quite common operation to convert a list into a map with particular key. For example, convert a list

to a map

We have 2 ways to do this in Java. One way is good-old days for-loop.

Alternative is to use stream() interface like

Then, what’s the difference between the former and the latter ?

O.K. An example below illustrate the answer.

Yes, duplicate key. The former implementation of loop will override the values on the duplicated key, while the latter implementation will throw java.lang.IllegalStateException: Duplicate key exception.

There is a related question on stackoverflow. Looks like people tends to overlook the duplicate key case (sorry, that’s me honestly.). I feel like this is another benefit to use stream() interface as it reminds us of these corner cases.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response