What’s the difference between
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.