Categories
collections java

HashMap in java with example

HashMap in java with example

In this tutorial we will learn about HashMap in java with example

Hashmap is used store key and value pair in java which implemented map interface internally

Features

  • It will not allow duplicate keys
  • We can store null value as a key
  • It is not thread safe

Example


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

public class HashmapExample {
	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());
			}
			System.out.println("---------------");
			// 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

1 Value is Car
2 Value is Bus
3 Value is Train
---------------
Value of 1 is Car
Value of 2 is Bus
Value of 3 is Train

Reference

https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
https://beginnersbug.com/check-key-exists-in-hashmap-java/

Download

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

Leave a Reply

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