Вы находитесь на странице: 1из 5

HashMap Example in Java:

In this example we have demonstrate almost all the important methods of


HashMap class.
package beginnersbook.com;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
public class Details {
public static void main(String args[]) {
/* This is how to declare HashMap */
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
/*Adding elements to HashMap*/
hmap.put(12, "Chaitanya");
hmap.put(2, "Rahul");
hmap.put(7, "Singh");
hmap.put(49, "Ajeet");
hmap.put(3, "Anuj");
/* Display content using Iterator*/
Set set = hmap.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry)iterator.next();
System.out.print("key is: "+ mentry.getKey() + " & Value is: ");
System.out.println(mentry.getValue());
}
/* Get values based on key*/
String var= hmap.get(2);
System.out.println("Value at index 2 is: "+var);
/* Remove values based on key*/
hmap.remove(3);
System.out.println("Map key and values after removal:");
Set set2 = hmap.entrySet();
Iterator iterator2 = set2.iterator();
while(iterator2.hasNext()) {
Map.Entry mentry2 = (Map.Entry)iterator2.next();
System.out.print("Key is: "+mentry2.getKey() + " & Value is: ");
System.out.println(mentry2.getValue());
}
}
}

HashMap Single Key


and Multiple Values
Example
SomeHashMap can be used to store key-value pairs.
But sometimes you may want to store multiple values for the same
key.
For example:
For Key A, you want to store - Apple, Aeroplane
For Key B, you want to store - Bat, Banana
For Key C, you want to store Cat, Car
The following code snippets will show you at least 3 different ways of
storing key-value pairs with a distinction of Single Key and Multiple
Values

HashMap Single Key and Multiple Values


Using List
package com.skilledmonster.examples.util.map;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* HashMap - Single Key and Multiple Values using List
*
* @author Jagadeesh Motamarri
* @version 1.0
*/
public class SingleKeyMultipleValueUsingList {
public static void main(String[] args) {
// create map to store

Map<String, List<String>> map = new HashMap<String,


List<String>>();
// create list one and store values
List<String> valSetOne = new ArrayList<String>();
valSetOne.add("Apple");
valSetOne.add("Aeroplane");
// create list two and store values
List<String> valSetTwo = new ArrayList<String>();
valSetTwo.add("Bat");
valSetTwo.add("Banana");
// create list three and store values
List<String> valSetThree = new ArrayList<String>();
valSetThree.add("Cat");
valSetThree.add("Car");
// put values into map
map.put("A", valSetOne);
map.put("B", valSetTwo);
map.put("C", valSetThree);
// iterate and display values
System.out.println("Fetching Keys and corresponding [Multiple]
Values n");
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
String key = entry.getKey();
List<String> values = entry.getValue();
System.out.println("Key = " + key);
System.out.println("Values = " + values + "n");
}
}
}

times you want to store multiple values for the same


hash key.

Difference between list set


and map in java?
CHAITANYA SINGH | FILED UNDER: JAVA COLLECTIONS | UPDATED: JANUARY 2, 2015

List, Set and Map are the interfaces which implements Collection interface. Here
we will discuss difference between List Set and Map in Java.

List Vs Set Vs Map


1) Duplicity: List allows duplicate elements. Any number of duplicate elements can
be inserted into the list without affecting the same existing values and their
indexes.

Set doesnt allow duplicates. Set and all of the classes which implements Set
interface should have unique elements.
Map stored the elements as key & value pair. Map doesnt allow duplicate keys
while it allows duplicate values.
2) Null values: List allows any number of null values.
Set allows single null value at most.
Map can have single null key at most and any number of null values.
3) Order: List and all of its implementation classes maintains the insertion order.
Set doesnt maintain any order; still few of its classes sort the elements in an
order such as LinkedHashSet maintains the elements in insertion order.
Similar to Set Map also doesnt stores the elements in an order, however few of its
classes does the same. For e.g. TreeMap sorts the map in the ascending order of
keys and LinkedHashMap sorts the elements in the insertion order, the order in
which the elements got added to the LinkedHashMap.
4) Commonly used classes:
List: ArrayList, LinkedList etc.
Set: HashSet, LinkedHashSet, TreeSet, SortedSet etc.
Map: HashMap, TreeMap, WeakHashMap, LinkedHashMap, IdentityHashMap etc.

When to use List, Set and Map in Java?


1) If you do not want to have duplicate values in the database then Set should be
your first choice as all of its classes do not allow duplicates.
2) If there is a need of frequent search operations based on the index values then
List (ArrayList) is a better choice.
3) If there is a need of maintaining the insertion order then also the List is a
preferred collection interface.
4) If the requirement is to have the key & value mappings in the database then
Map is your best bet.

Difference between List and Set


Differences between List<E> and Set<E>

List<E> and Set<E> are part of Java CollectionsFramework and are used widely. Most common
implementation of List<E> is ArrayList<E> and for Set<E> is HashSet<E>. There are few differences
between the two and in this post we will see them.

This post is part of Java Collections Interview Questionsand you can find several interview questions
here.

List<E> and Set<E> difference.

First difference is that List<E> allows you to insert duplicate elements. While Set<E> isnt
kind enough to let you insert duplicate elements. If you try to value that exists in Set<E> then it will
replace that value. Set<E> contains unique elements.

Second difference is that List<E> maintains the order of Insertion. As discussed here List<E>
maintains the order of insertion of elements. Set<E> does not maintain order. But we can use
SortedSet<E> which can store elements defined by Comparator<T>. LinkedHashSet<E>(concrete
implementation of Set<E>) allows you to maintain the insertion order but does not allow indexed
access.

Third difference is in terms of index access or Random access of elements. List<E> interface
has ArrayList<E> as concrete implementation. ArrayList<E> is backed by an array and hence it
supports indexed retrieval of elements. This cannot be achieved by any concrete implementation of
Set<E>.

Fourth difference is that we can use Iterator<E> and ListIterator<E> to iterate through the
List<E>. For Set<E> we can only use Iterator<E> interface.

Вам также может понравиться