Categories
collections java

get key and value from hashmap in java

In this tutorial, we will learn about get key and value from hashmap in java

Example Using Java 8

import java.util.HashMap;
import java.util.Map;

public class KeyValueFromHashMap {

	public static void main(String[] args) {
		try {
			Map<String, String> hashMap = new HashMap();
			hashMap.put("1", "Car");
			hashMap.put("2", "Bus");
			hashMap.put("3", "Train");

			// Below code only work above java 8
			hashMap.forEach((key, value) -> {
				System.out.println("Value of " + key + " is " + value);
			});

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Output
Value of 1 is Car
Value of 2 is Bus
Value of 3 is Train
Example using java 7

import java.util.HashMap;
import java.util.Map;

public class KeyValueFromHashMap {

	public static void main(String[] args) {
		try {
			Map<String, String> hashMap = new HashMap();
			hashMap.put("1", "Car");
			hashMap.put("2", "Bus");
			hashMap.put("3", "Train");

			for (Map.Entry<String, String> entry : hashMap.entrySet()) {
				System.out.println(entry.getKey() + " Value is " + entry.getValue());
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Output
1 Value is Car
2 Value is Bus
3 Value is Train
GitHub Url

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/KeyValueFromHashMap.java

Related Articles

Check key exists in Hashmap Java

Categories
collections java

Check key exists in Hashmap Java

Check key exists in Hashmap Java

In below example we are going to Check key exists in Hashmap java

Syntax

<span class="token function">containsKey</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

Example

import java.util.HashMap;
import java.util.Map;

public class KeyExistsHashMapExample {

  public static void main(String[] args) {
    Map<String, String> hashMap = new HashMap<String, String>();
    hashMap.put("1", "Car");
    hashMap.put("2", "Bus");
    hashMap.put("3", "Train");
    boolean isKeyAvaillable = hashMap.containsKey("1");
    if(isKeyAvaillable) {
      System.out.println("The value is "+hashMap.get("1"));
    }
    else {
      System.out.println("Key is not availlable");
    }
  }
}

Output

The value is Car

Reference

https://beginnersbug.com/hashmap-in-java/
https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#containsKey-java.lang.Object-

Download

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/KeyExistsHashMapExample.java