Java Map values() Method Tutorial

In this section, we will learn what the Map values() method is and how to use it in Java.

What is Java Map values() Method?

The Java Map values() method is used to get a Collection “view” of the values in a Map object.

Note: we say a “view” and not a copy! This means both the map object and the returned collection from the method are linked to the same values. So if one changed a value, the other will see.

Java values() Method Syntax:

Collection<V> values()

values() Method Parameters:

The method does not take an argument.

values() Method Return Value:

The return value of this method is an object of type Collection.

values() Method Exceptions:

The method does not throw an exception.

Example: using Map values() method

import java.util.Map; 
import java.util.HashMap;
import java.util.Iterator; 
class Main{
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<>();
        map.put("Omid","Dehghan");
        map.put("Jack","Bauer");
        map.put("Barack","Obama");
        map.put("Elon","Musk");
        map.put("Lex","Fridman");

        Iterator<String> it = map.values().iterator();

        while(it.hasNext()){
            System.out.println(it.next());
        }
    }
}

Output:

Musk

Obama

Dehghan

Bauer

Fridman
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies