How To Retrieve Key And Values From HashMap In Java 8

By | March 11, 2024

In Java 8, we can retrieve the Keys and Values in Various ways. Here we will provide all the ways to retrieve the keys and Values from the Hashmap.

Here we use in 4 ways

  1. forEach
  2. keySet
  3. entrySet
  4. stream
package com.example.test;

import java.util.HashMap;
import java.util.stream.Collectors;

public class HashMapGetDemo {
	public static void main(String[] args) {
		
		HashMap<String, Integer> map = new HashMap<>();
		map.put("Siva", 20);
		map.put("Raju", 30);
		map.put("Lokesh", 40);
		
		//Method 1: use for each
		System.out.println("Method1: Use for each");
		map.forEach((key,value)-> System.out.println("Key is: "+ key + " Value is: "+ value));
		
		//Method2: Use keyset and foreach to iterate
		System.out.println("Method2: Use keyset and foreach");
		map.keySet().forEach(key-> System.out.println("Key is: "+ key + "Value is: "+ map.get(key)));
		
		//Method3: Use entrySet and foreach
		System.out.println("Method3: Use entryset and Foreach ");
		map.entrySet().forEach(entry->System.out.println("Key is: "+entry.getKey() + "Value is: "+ entry.getValue()));
		
		//Method4: Use Streams
		System.out.println("Method4: Using Streams");
		String keys= map.keySet().stream().map(Object::toString).collect(Collectors.joining(", "));
		String values = map.values().stream().map(Object::toString).collect(Collectors.joining(", "));
		System.out.println("Keys : "+keys);
		System.out.println("Values: "+values);
	}

}

Leave a Reply

Your email address will not be published. Required fields are marked *