Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java

What is the values() method of the HashMap class in Java?

Talha Ashar

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

The values() method of the HashMap class in Java returns a Collection view of the values present in a HashMap instance.

The process is illustrated below:

To use the values() method, you will need to import the HashMap class into the program, as shown below:

import java.util.HashMap;

The prototype of the values() method is shown below:

public Collection<V> values()

Parameters

The values() method does not take any parameters.

Return value

The values() method returns a Collection view of the values present in a HashMap instance.

If there are duplicate values in the HashMap, they are all returned as part of the view.

Example

The code below shows how the values() method works in Java:

import java.util.HashMap;
class Main {
public static void main(String[] args)
{
// initializing HashMap
HashMap<String, Integer> vehicles = new HashMap<>();
// populating HashMap
vehicles.put("Car", 1);
vehicles.put("Bus", 2);
vehicles.put("Truck", 3);
vehicles.put("Bike", 1);
// view all values in the HashMap
System.out.println("The HashMap contains the following values: " + vehicles.values());
}
}

Explanation

First, a HashMap object vehicles is initialized.

Next, key-value pairs are inserted into the HashMap. The value 11 is used for two entries: “Car” and “Bike”. All other entries have unique values.

The values method in line 1616 proceeds to return a Collection view of all the values in the HashMap. The HashMap contains a duplicate for the value 11, so the view contains two occurrences of the value 11.

RELATED TAGS

java

CONTRIBUTOR

Talha Ashar
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring