Java HashMap key value storage and retrieval - java

I want to store values and retrieve them from a Java HashMap.
This is what I have so far:
public void processHashMap()
{
HashMap hm = new HashMap();
hm.put(1,"godric gryfindor");
hm.put(2,"helga hufflepuff");
hm.put(3,"rowena ravenclaw");
hm.put(4,"salazaar slytherin");
}
I want to retrieve all Keys and Values from the HashMap as a Java Collection or utility set (for example LinkedList).
I know I can get the value if I know the key, like this:
hm.get(1);
Is there a way to retrieve key values as a list?

I use these three ways to iterate a map. All methods (keySet, values, entrySet) return a collection.
// Given the following map
Map<KeyClass, ValueClass> myMap;
// Iterate all keys
for (KeyClass key : myMap.keySet())
System.out.println(key);
// Iterate all values
for (ValueClass value : myMap.values())
System.out.println(value);
// Iterate all key/value pairs
for (Entry<KeyClass, ValueClass> entry : myMap.entrySet())
System.out.println(entry.getKey() + " - " + entry.getValue());
Since Java 8 i often use Streams with lambda expressions.
// Iterate all keys
myMap.keySet().stream().forEach(key -> System.out.println(key));
// Iterate all values
myMap.values().parallelStream().forEach(value -> System.out.println(value));
// Iterate all key/value pairs
myMap.entrySet().stream().forEach(entry -> System.out.println(entry.getKey() + " - " + entry.getValue()));

Java Hashmap key value example:
public void processHashMap() {
//add keys->value pairs to a hashmap:
HashMap hm = new HashMap();
hm.put(1, "godric gryfindor");
hm.put(2, "helga hufflepuff");
hm.put(3, "rowena ravenclaw");
hm.put(4, "salazaar slytherin");
//Then get data back out of it:
LinkedList ll = new LinkedList();
Iterator itr = hm.keySet().iterator();
while(itr.hasNext()) {
String key = itr.next();
ll.add(key);
}
System.out.print(ll); //The key list will be printed.
}

map.keySet() would give you all the keys

//import statements
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeMap;
// hashmap test class
public class HashMapTest {
public static void main(String args[]) {
HashMap<Integer,String> hashMap = new HashMap<Integer,String>();
hashMap.put(91, "India");
hashMap.put(34, "Spain");
hashMap.put(63, "Philippines");
hashMap.put(41, "Switzerland");
// sorting elements
System.out.println("Unsorted HashMap: " + hashMap);
TreeMap<Integer,String> sortedHashMap = new TreeMap<Integer,String>(hashMap);
System.out.println("Sorted HashMap: " + sortedHashMap);
// hashmap empty check
boolean isHashMapEmpty = hashMap.isEmpty();
System.out.println("HashMap Empty: " + isHashMapEmpty);
// hashmap size
System.out.println("HashMap Size: " + hashMap.size());
// hashmap iteration and printing
Iterator<Integer> keyIterator = hashMap.keySet().iterator();
while(keyIterator.hasNext()) {
Integer key = keyIterator.next();
System.out.println("Code=" + key + " Country=" + hashMap.get(key));
}
// searching element by key and value
System.out.println("Does HashMap contains 91 as key: " + hashMap.containsKey(91));
System.out.println("Does HashMap contains India as value: " + hashMap.containsValue("India"));
// deleting element by key
Integer key = 91;
Object value = hashMap.remove(key);
System.out.println("Following item is removed from HashMap: " + value);
}
}

You can use keySet() to retrieve the keys.
You should also consider adding typing in your Map, e.g :
Map<Integer, String> hm = new HashMap<Integer, String>();
hm.put(1,"godric gryfindor");
hm.put(2,"helga hufflepuff");
hm.put(3,"rowena ravenclaw");
hm.put(4,"salazaar slytherin");
Set<Integer> keys = hm.keySet();

void hashMapExample(){
HashMap<String, String> hMap = new HashMap<String, String>();
hMap.put("key1", "val1");
hMap.put("key2", "val2");
hMap.put("key3", "val3");
hMap.put("key4", "val4");
hMap.put("key5", "val5");
if(hMap != null && !hMap.isEmpty()){
for(String key : hMap.keySet()){
System.out.println(key+":"+hMap.get(key));
}
}
}

Related

printing a hashmap of a key with multiple values

class hello {
string name;
int number;
}
class object {
public static void main(string args[]) {
HashMap hs = new HashMap();
hello c1 = new hello();
hello c2 = new hello();
hs.put("india",c1);
hs.put("america",c2);
}
}
how to print he key value pairs
key with multiple values how is it printed
Iterate Map or HashMap like this.
Map<String, Hello> map=new HashMap<>();
Set<Entry<String, Hello>> entries=map.entrySet();
for (Entry<String, Hello> entry : entries) {
String key=entry.getKey();
Hello hello=entry.getValue();
}
With Java 8:
map.forEach((key, value) -> System.out.println(key + ", " + value));
You need to iterate over hash map keys, then print the key with its value.
Example:
HashMap<String, hello> map = new HashMap<String, hello>();
for (Iterator<String> iterator = map.keySet().iterator(); iterator.hasNext();) {
String key = iterator.next();
System.out.println(key + map.get(keu).toString); suppose you already override the toString method in your hello class
}
You can iterate using Entry Set too.
HashMap<String,hello> hs=new HashMap<String, hello>();
// Put values for hashMap.
for(Map.Entry<String, hello> printPairs: hs.entrySet()) {
System.out.print(printPairs.getKey()+" ---- ");
System.out.println(printPairs.getValue());
}

Print all key/value pairs in a Java ConcurrentHashMap

I am trying to simply print all key/value pair(s) in a ConcurrentHashMap.
I found this code online that I thought would do it, but it seems to be getting information about the buckets/hashcode. Actually to be honest the output it quite strange, its possible my program is incorrect, but I first want to make sure this part is what I want to be using.
for (Entry<StringBuilder, Integer> entry : wordCountMap.entrySet()) {
String key = entry.getKey().toString();
Integer value = entry.getValue();
System.out.println("key, " + key + " value " + value);
}
This gives output for about 10 different keys, with counts that seem to be the sum of the number of total inserts into the map.
I tested your code and works properly. I've added a small demo with another way to print all the data in the map:
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
for (String key : map.keySet()) {
System.out.println(key + " " + map.get(key));
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey().toString();
Integer value = entry.getValue();
System.out.println("key, " + key + " value " + value);
}
The HashMap has forEach as part of its structure. You can use that with a lambda expression to print out the contents in a one liner such as:
map.forEach((k,v)-> System.out.println(k+", "+v));
or
map.forEach((k,v)-> System.out.println("key: "+k+", value: "+v));
You can do something like
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next().toString();
Integer value = map.get(key);
System.out.println(key + " " + value);
}
Here 'map' is your concurrent HashMap.
//best and simple way to show keys and values
//initialize map
Map<Integer, String> map = new HashMap<Integer, String>();
//Add some values
map.put(1, "Hi");
map.put(2, "Hello");
// iterate map using entryset in for loop
for(Entry<Integer, String> entry : map.entrySet())
{ //print keys and values
System.out.println(entry.getKey() + " : " +entry.getValue());
}
//Result :
1 : Hi
2 : Hello
The ConcurrentHashMap is very similar to the HashMap class, except that ConcurrentHashMap offers internally maintained concurrency. It means you do not need to have synchronized blocks when accessing ConcurrentHashMap in multithreaded application.
To get all key-value pairs in ConcurrentHashMap, below code which is similar to your code works perfectly:
//Initialize ConcurrentHashMap instance
ConcurrentHashMap<String, Integer> m = new ConcurrentHashMap<String, Integer>();
//Print all values stored in ConcurrentHashMap instance
for each (Entry<String, Integer> e : m.entrySet()) {
System.out.println(e.getKey()+"="+e.getValue());
}
Above code is reasonably valid in multi-threaded environment in your application. The reason, I am saying 'reasonably valid' is that, above code yet provides thread safety, still it can decrease the performance of application.
Hope this helps you.
Work 100% sure try this code for the get all hashmap key and value
static HashMap<String, String> map = new HashMap<>();
map.put("one" " a " );
map.put("two" " b " );
map.put("three" " c " );
map.put("four" " d " );
just call this method whenever you want to show the HashMap value
private void ShowHashMapValue() {
/**
* get the Set Of keys from HashMap
*/
Set setOfKeys = map.keySet();
/**
* get the Iterator instance from Set
*/
Iterator iterator = setOfKeys.iterator();
/**
* Loop the iterator until we reach the last element of the HashMap
*/
while (iterator.hasNext()) {
/**
* next() method returns the next key from Iterator instance.
* return type of next() method is Object so we need to do DownCasting to String
*/
String key = (String) iterator.next();
/**
* once we know the 'key', we can get the value from the HashMap
* by calling get() method
*/
String value = map.get(key);
System.out.println("Key: " + key + ", Value: " + value);
}
}

Iterator over HashMap in Java

I tried to iterate over hashmap in Java, which should be a fairly easy thing to do. However, the following code gives me some problems:
HashMap hm = new HashMap();
hm.put(0, "zero");
hm.put(1, "one");
Iterator iter = (Iterator) hm.keySet().iterator();
while(iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
System.out.println(entry.getKey() + " - " + entry.getValue());
}
First, I needed to cast Iterator on hm.keySet().iterator(), because otherwise it said "Type mismatch: cannot convert from java.util.Iterator to Iterator". But then I get "The method hasNext() is undefined for the type Iterator", and "The method hasNext() is undefined for the type Iterator".
Can we see your import block? because it seems that you have imported the wrong Iterator class.
The one you should use is java.util.Iterator
To make sure, try:
java.util.Iterator iter = hm.keySet().iterator();
I personally suggest the following:
Map Declaration using Generics and declaration using the Interface Map<K,V> and instance creation using the desired implementation HashMap<K,V>
Map<Integer, String> hm = new HashMap<>();
and for the loop:
for (Integer key : hm.keySet()) {
System.out.println("Key = " + key + " - " + hm.get(key));
}
UPDATE 3/5/2015
Found out that iterating over the Entry set will be better performance wise:
for (Map.Entry<Integer, String> entry : hm.entrySet()) {
Integer key = entry.getKey();
String value = entry.getValue();
}
UPDATE 10/3/2017
For Java8 and streams, your solution will be (Thanks #Shihe Zhang)
hm.forEach((key, value) -> System.out.println(key + ": " + value))
You should really use generics and the enhanced for loop for this:
Map<Integer, String> hm = new HashMap<>();
hm.put(0, "zero");
hm.put(1, "one");
for (Integer key : hm.keySet()) {
System.out.println(key);
System.out.println(hm.get(key));
}
http://ideone.com/sx3F0K
Or the entrySet() version:
Map<Integer, String> hm = new HashMap<>();
hm.put(0, "zero");
hm.put(1, "one");
for (Map.Entry<Integer, String> e : hm.entrySet()) {
System.out.println(e.getKey());
System.out.println(e.getValue());
}
With Java 8:
hm.forEach((k, v) -> {
System.out.println("Key = " + k + " - " + v);
});
Several problems here:
You probably don't use the correct iterator class. As others said, use import java.util.Iterator
If you want to use Map.Entry entry = (Map.Entry) iter.next(); then you need to use hm.entrySet().iterator(), not hm.keySet().iterator(). Either you iterate on the keys, or on the entries.
Map<String, Car> carMap = new HashMap<String, Car>(16, (float) 0.75);
// there is no iterator for Maps, but there are methods to do this.
Set<String> keys = carMap.keySet(); // returns a set containing all the keys
for(String c : keys)
{
System.out.println(c);
}
Collection<Car> values = carMap.values(); // returns a Collection with all the objects
for(Car c : values)
{
System.out.println(c.getDiscription());
}
/*keySet and the values methods serve as “views” into the Map.
The elements in the set and collection are merely references to the entries in the map,
so any changes made to the elements in the set or collection are reflected in the map, and vice versa.*/
//////////////////////////////////////////////////////////
/*The entrySet method returns a Set of Map.Entry objects.
Entry is an inner interface in the Map interface.
Two of the methods specified by Map.Entry are getKey and getValue.
The getKey method returns the key and getValue returns the value.*/
Set<Map.Entry<String, Car>> cars = carMap.entrySet();
for(Map.Entry<String, Car> e : cars)
{
System.out.println("Keys = " + e.getKey());
System.out.println("Values = " + e.getValue().getDiscription() + "\n");
}
The cleanest way is to not (directly) use an iterator at all:
type your map with generics
use a foreach loop to iterate over the entries:
Like this:
Map<Integer, String> hm = new HashMap<Integer, String>();
hm.put(0, "zero");
hm.put(1, "one");
for (Map.Entry<Integer, String> entry : hm.entrySet()) {
// do something with the entry
System.out.println(entry.getKey() + " - " + entry.getValue());
// the getters are typed:
Integer key = entry.getKey();
String value = entry.getValue();
}
This is way more efficient than iterating over keys, because you avoid n calls to get(key).
You are getting a keySet iterator on the HashMap and expecting to iterate over entries.
Correct code:
HashMap hm = new HashMap();
hm.put(0, "zero");
hm.put(1, "one");
//Here we get the keyset iterator not the Entry iterator
Iterator iter = (Iterator) hm.keySet().iterator();
while(iter.hasNext()) {
//iterator's next() return an Integer that is the key
Integer key = (Integer) iter.next();
//already have the key, now get the value using get() method
System.out.println(key + " - " + hm.get(key));
}
Iterating over a HashMap using EntrySet:
HashMap hm = new HashMap();
hm.put(0, "zero");
hm.put(1, "one");
//Here we get the iterator on the entrySet
Iterator iter = (Iterator) hm.entrySet().iterator();
//Traversing using iterator on entry set
while (iter.hasNext()) {
Entry<Integer,String> entry = (Entry<Integer,String>) iter.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
System.out.println();
//Iterating using for-each construct on Entry Set
Set<Entry<Integer, String>> entrySet = hm.entrySet();
for (Entry<Integer, String> entry : entrySet) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Look at the section -Traversing Through a HashMap in the below link.
java-collection-internal-hashmap and Traversing through HashMap
Iterator through keySet will give you keys. You should use entrySet if you want to iterate entries.
HashMap hm = new HashMap();
hm.put(0, "zero");
hm.put(1, "one");
Iterator iter = (Iterator) hm.entrySet().iterator();
while(iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
System.out.println(entry.getKey() + " - " + entry.getValue());
}

How to iterate through LinkedHashMap with lists as values

I have following LinkedHashMap declaration.
LinkedHashMap<String, ArrayList<String>> test1
my point is how can i iterate through this hash map.
I want to do this following, for each key get the corresponding arraylist and print the values of the arraylist one by one against the key.
I tried this but get only returns string,
String key = iterator.next().toString();
ArrayList<String> value = (ArrayList<String> )test1.get(key)
for (Map.Entry<String, ArrayList<String>> entry : test1.entrySet()) {
String key = entry.getKey();
ArrayList<String> value = entry.getValue();
// now work with key and value...
}
By the way, you should really declare your variables as the interface type instead, such as Map<String, List<String>>.
I'm assuming you have a typo in your get statement and that it should be test1.get(key). If so, I'm not sure why it is not returning an ArrayList unless you are not putting in the correct type in the map in the first place.
This should work:
// populate the map
Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.put("key1", new ArrayList<String>());
test1.put("key2", new ArrayList<String>());
// loop over the set using an entry set
for( Map.Entry<String,List<String>> entry : test1.entrySet()){
String key = entry.getKey();
List<String>value = entry.getValue();
// ...
}
or you can use
// second alternative - loop over the keys and get the value per key
for( String key : test1.keySet() ){
List<String>value = test1.get(key);
// ...
}
You should use the interface names when declaring your vars (and in your generic params) unless you have a very specific reason why you are defining using the implementation.
In Java 8:
Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.forEach((key,value) -> {
System.out.println(key + " -> " + value);
});
You can use the entry set and iterate over the entries which allows you to access both, key and value, directly.
for (Entry<String, ArrayList<String>> entry : test1.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
I tried this but get only returns string
Why do you think so? The method get returns the type E for which the generic type parameter was chosen, in your case ArrayList<String>.
// iterate over the map
for(Entry<String, ArrayList<String>> entry : test1.entrySet()){
// iterate over each entry
for(String item : entry.getValue()){
// print the map's key with each value in the ArrayList
System.out.println(entry.getKey() + ": " + item);
}
}

Iterate through a HashMap [duplicate]

This question already has answers here:
How do I efficiently iterate over each entry in a Java Map?
(46 answers)
Closed 3 years ago.
What's the best way to iterate over the items in a HashMap?
If you're only interested in the keys, you can iterate through the keySet() of the map:
Map<String, Object> map = ...;
for (String key : map.keySet()) {
// ...
}
If you only need the values, use values():
for (Object value : map.values()) {
// ...
}
Finally, if you want both the key and value, use entrySet():
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// ...
}
One caveat: if you want to remove items mid-iteration, you'll need to do so via an Iterator (see karim79's answer). However, changing item values is OK (see Map.Entry).
Iterate through the entrySet() like so:
public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}
Read more about Map.
Extracted from the reference How to Iterate Over a Map in Java:
There are several ways of iterating over a Map in Java. Let's go over the most common methods and review their advantages and disadvantages. Since all maps in Java implement the Map interface, the following techniques will work for any map implementation (HashMap, TreeMap, LinkedHashMap, Hashtable, etc.)
Method #1: Iterating over entries using a For-Each loop.
This is the most common method and is preferable in most cases. It should be used if you need both map keys and values in the loop.
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Note that the For-Each loop was introduced in Java 5, so this method is working only in newer versions of the language. Also a For-Each loop will throw NullPointerException if you try to iterate over a map that is null, so before iterating you should always check for null references.
Method #2: Iterating over keys or values using a For-Each loop.
If you need only keys or values from the map, you can iterate over keySet or values instead of entrySet.
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
// Iterating over keys only
for (Integer key : map.keySet()) {
System.out.println("Key = " + key);
}
// Iterating over values only
for (Integer value : map.values()) {
System.out.println("Value = " + value);
}
This method gives a slight performance advantage over entrySet iteration (about 10% faster) and is more clean.
Method #3: Iterating using Iterator.
Using Generics:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<Integer, Integer> entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Without Generics:
Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
Integer key = (Integer)entry.getKey();
Integer value = (Integer)entry.getValue();
System.out.println("Key = " + key + ", Value = " + value);
}
You can also use same technique to iterate over keySet or values.
This method might look redundant, but it has its own advantages. First of all, it is the only way to iterate over a map in older versions of Java. The other important feature is that it is the only method that allows you to remove entries from the map during iteration by calling iterator.remove(). If you try to do this during For-Each iteration you will get "unpredictable results" according to Javadoc.
From a performance point of view this method is equal to a For-Each iteration.
Method #4: Iterating over keys and searching for values (inefficient).
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer key : map.keySet()) {
Integer value = map.get(key);
System.out.println("Key = " + key + ", Value = " + value);
}
This might look like a cleaner alternative for method #1, but in practice it is pretty slow and inefficient as getting values by a key might be time-consuming (this method in different Map implementations is 20%-200% slower than method #1). If you have FindBugs installed, it will detect this and warn you about inefficient iteration. This method should be avoided.
Conclusion:
If you need only keys or values from the map, use method #2. If you are stuck with older version of Java (less than 5) or planning to remove entries during iteration, you have to use method #3. Otherwise use method #1.
for (Map.Entry<String, String> item : hashMap.entrySet()) {
String key = item.getKey();
String value = item.getValue();
}
You can iterate through the entries in a Map in several ways. Get each key and value like this:
Map<?,?> map = new HashMap<Object, Object>();
for(Entry<?, ?> e: map.entrySet()){
System.out.println("Key " + e.getKey());
System.out.println("Value " + e.getValue());
}
Or you can get the list of keys with
Collection<?> keys = map.keySet();
for(Object key: keys){
System.out.println("Key " + key);
System.out.println("Value " + map.get(key));
}
If you just want to get all of the values and aren't concerned with the keys, you can use:
Collection<?> values = map.values();
Smarter:
for (String key : hashMap.keySet()) {
System.out.println("Key: " + key + ", Value: " + map.get(key));
}
It depends. If you know you're going to need both the key and the value of every entry, then go through the entrySet. If you just need the values, then there's the values() method. And if you just need the keys, then use keyset().
A bad practice would be to iterate through all of the keys, and then within the loop, always do map.get(key) to get the value. If you're doing that, then the first option I wrote is for you.

Categories