Java Access Elements in Hashmap

h‮:sptt‬//www.lautturi.com
Java Access Elements in Hashmap
/**
 * @author lautturi.com 
 * Java example: java hashmap example access element
 */

import java.util.*;

public class Lautturi {

	public static void main(String[] args) {

		// Creating a HashMap
		HashMap<Integer, String> map = new HashMap<Integer, String>();
		
		// Put elements in Map
		map.put(1,"Apple"); 
		map.put(2,"Banana");
		map.put(3,"Cherry");
		map.put(4,"Orange");
		map.put(5,"Lautturi");

		// print hashmap
		for (Map.Entry m : map.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		// access element using get() method
		String value = map.get(2);
		System.out.println("Value at index 2: " + value);

	}
}

output:

1 Apple
2 Banana
3 Cherry
4 Orange
5 Lautturi
Value at index 2: Banana
Created Time:2017-09-24 22:38:24  Author:lautturi