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

Categories
collections java

ArrayList in java with example

 

In this tutorial we will learn ArrayList in java with example 

In Java we can achieve the dynamic array using arraylist.
ArrayList class available on util package, so we don’t need to import any extra packages, In below example 

  • created new arraylist
  • added value to arraylist
  • printing the array list value by using for loop 

Example

import java.util.ArrayList;
import java.util.List;

public class ArrayListExample {
	  public static void main(String[] args) {
      List arrayList = new ArrayList();
      arrayList.add("Java");
      arrayList.add("Java 8");
      arrayList.add("Java 11");
      for (int i = 0; i < arrayList.size(); i++) {
    System.out.println("Value at the index of " + i + " "+arrayList.get(i));
     }
   }
}

Output

Value at the index of 0 Java
Value at the index of 1 Java 8
Value at the index of 2 Java 11
Github

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

Related Articles

Sort an Arraylist in java with example

iterate stream with index in Java8