Difference between Pair and Hashmap?

Viewed 17022

What is the necessity to introduce Pair class when Hashmap can do the same job?

I see Pair being introduced to Java version 8

3 Answers

A pair is basically a convenient way of associating a simple key to a value. Maps do the same thing to store key-value pairs but maps stores a collection of pairs and operate them as a whole.

Number of times we have a requirement where a key-value pair shall exist on its own, for instance:

  • A key-value pair needs to be passed to a method as an argument, Or
  • A method needs to return just two values in form of a pair

Map complicates the things when we just need a single pair of key-value.

Related