Share on Google+Share on Google+

Collection : HashMap Example

This tutorial will help you in understanding of HashMap concept.

Collection : HashMap Example

This tutorial will help you in understanding of HashMap concept.

HashMap :

The java.util.HashMap class implements Map interface. It gives you an unsorted, unordered Map. It provides unique keys to each values that is each value has unique key through which we can retrieve corresponding value. HashMap can allow multiple null key and multiple null value in a collection.

Methods : Following are some methods -

put(K key, V value) : It associates the given value with the given key in the HashMap.

get(Object key) : It returns the value corresponding to the specified key. It returns null if key does not exist.

keySet() : This method returns a set view of all the keys exist in the HashMap.

values() : It returns a Collection view of all the values exist in the HashMap.

Other methods are - clear(), clone(), containsKey(Object key), containsValue(Object value), entrySet(), isEmpty(), putAll(Map<? extends K,? extends V> m), remove(Object key), size() .

Example :

package collection;

import java.util.HashMap;

class HashMapExample{
public static void main(String[] args){
HashMap map=new HashMap();

map.put(3, "Peach");

System.out.println("Size of HashMap : "+map.size());
System.out.println("key and values of HashMap : "+map);
System.out.println("values of HashMap : "+map.values());
System.out.println("keyset of HashMap : "+map.keySet());

Description : In this example we are creating HashMap as - HashMap map=new HashMap();
In HashMap for adding new element we use put(key,value). Here we input key and corresponding value. By using size() method we can find out number of elements in the map. map.keySet() method displays all the keys of map and map.values() method displays all the values of map.

Output :

Size of HashMap : 3
key and values of HashMap : {1=Mango, 2=orange, 3=Peach}
values of HashMap : [Mango, orange, Peach]
keyset of HashMap : [1, 2, 3]



Posted on: November 9, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null