Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

linkedhashmap
java
communitycreator

What is the LinkedHashMap.values() method in Java?

Programming Bytes

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.

The LinkedHashMap class in Java is the same as the HashMap class, except that the LinkedHashMap maintains the insertion order, whereas the HashMap doesn’t. Internally, the LinkedHashMap class uses a doubly-linked list to maintain the insertion order.

You can read more about the LinkedHashMap class here.

What is the values() method?

The values() method of the LinkedHashMap class returns the Collection view of the values present in a LinkedHashMap object.

Syntax

public Collection<V> values()

This method doesn’t take any argument.

Code

The following code demonstrates how to use the values() method.

import java.util.LinkedHashMap;
import java.util.Collection;
class ValuesExample {
public static void main(String[] args) {
// create a LinkedHashMap
LinkedHashMap<Integer, String> numbers = new LinkedHashMap<>();
numbers.put(1, "One");
numbers.put(2, "Two");
System.out.println("The LinkedHashMap is - " + numbers);
Collection<String> values = numbers.values();
System.out.println("The values in LinkedHashMap is - " + values);
numbers.put(3, "Two");
System.out.println("The values in LinkedHashMap is - " + values);
}
}

Explanation

In the code above:

  • In line 1, we imported the LinkedHashMap class.

  • In line 7, we created a LinkedHashMap object with the name numbers.

  • In lines 9 and 10, we used the put() method to add two mappings ({1=one, 2=two}) to the LinkedHashMap object.

  • In line 13, we used the values() method of the LinkedHashMap to get the values present in numbers.

  • In line 16, we added a new entry (3 - "two") to the LinkedHashMap object.

  • In line 17, we printed the values variable. The newly added entry, two, will automatically be available in the values variable without the need to call the values() method because the previous call to the values() method returned the Collection view.

RELATED TAGS

linkedhashmap
java
communitycreator

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.

Keep Exploring