printing a hashmap of a key with multiple values - java

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());
}

Related

How to pass key of a value into variable in HashMap

Can I pass a key of a value into variable in hashmap?
For example I have a key 987456321 for value "A". How to pass the key in a variable so that I can further subdivide the key and print it as 987-654-321,
by taking 987 as first,
654 as middle,
321 as last
So that I can print
first+ "-" + middle+ "-" + last as 987-654-321
by using toString() method.
I am new to Java, So help me Please
public static void main(String[] args)
{
HashMap<Long, String> hashMap = new HashMap<>();
hashMap.put(987456321L, "A");
hashMap.put(321654998L, "B");
hashMap.put(874563210L, "C");
hashMap.put(987453216L, "B");
hashMap.put(321650123L, "C");
hashMap.put(874568745L, "C");
System.out.println("Size of Map:"+hashMap.size());
System.out.println("Enter no: ");
userInput = new Scanner(System.in);
no = userInput.nextLong();
String name = hashMap.get(no);
System.out.println(name);
for (Map.Entry<Long, String> entry : hashMap.entrySet())
{
String key = entry.getKey().toString();
String value = entry.getValue();
System.out.println("name " + value + "- Number " + key);
}
}
You can iterate over all key-value-pairs of your map like this:
for (final Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// do whatever you need to do with key
}
If you're interested in a key for a certain value only - makes not much sense as the same value might be stored in a map with different keys - you will need to check for the value in the above loop until you found the key-value-pair of interest. E.g.:
if (Objects.equals(value, "A")) {
// do something with the key for value "A"
}
1. Solution for specific value:
This method returns keys for your value
public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
Set<T> keys = new HashSet<T>();
for (Entry<T, E> entry : map.entrySet()) {
if (Objects.equals(value, entry.getValue())) {
keys.add(entry.getKey());
}
}
return keys;
}
Now all you have to do is to iterate through returned set and do what you want with variable which contains your key
for (Long key : set) {
String s = String.valueOf(key);
}

How to efficiently iterate a Multimap?

I have the following multimap:
Multimap<String,Multimap<String,Integer>> map = ArrayListMultimap.create();
I need to iterate it, but I am stuck.
How should I iterate it?
It looks like you are using google guava multimap and the create method of the class ArrayListMultimap to create it.
You can iterate through your multimap and your inner multimap like this:
package com.test.java;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
public class Main {
#SuppressWarnings("unchecked")
public static void main(String[] args) {
Multimap<String, Multimap<String,Integer>> map = ArrayListMultimap.create();
Multimap<String,Integer> m = ArrayListMultimap.create();
//put some values
m.put("value1", 1);
m.put("value2", 2);
m.put("value3", 3);
map.put("one", m);
for (Object value1 : map.values()) {
for (Object value2 : ((Multimap<String,Integer>)value1).values()) {
System.out.println((Integer)value2);
}
}
}
}
Output:
2
1
3
Note:
If you want to have a deterministic iteration order, use LinkedListMultimap:
Example:
LinkedListMultimap<String, LinkedListMultimap<String,Integer>> map = LinkedListMultimap.create();
LinkedListMultimap<String,Integer> m = LinkedListMultimap.create();
//put some values
m.put("value1", 1);
m.put("value2", 2);
m.put("value3", 3);
map.put("one", m);
for (Object value1 : map.values()) {
for (Object value2 : ((LinkedListMultimap<String,Integer>)value1).values()) {
System.out.println((Integer)value2);
}
}
Output:
1
2
3
Map<String, Multimap<String>> map = multimap.asMap();
System.out.println("Multimap as a map");
for (Map.Entry<String, Multimap<String>> entry : map.entrySet()) {
String key = entry.getKey();
Multimap<String> value = multimap.get("lower");
System.out.println(key + ":" + value);
}
please try it out.
my example
ListMultimap<Long, Long> items = elasticResult.getResult();
for (Long key : items.keySet()) {
items.get(key).forEach(value -> {
// ... use key and value
});
}

How to get specific values from an ArrayList of HashMaps

I have created an ArrayList of HashMaps and I know how to get all keys and values of all HashMaps in the list, but then I decided to make it complicated and iterate through the ArrayList and get only specific HashMap values(based on keys). I have no idea how to do that.
How can I modify printArrayList method to get only idand sku values from all hashmaps?
Right now I have the following example:
public class HashmapArraylist {
public static void main(String[] args) throws Exception {
Map<String, Object> map1 = new HashMap<>();
map1.put("id", 1);
map1.put("sku", "test1");
map1.put("quantity", 1);
Map<String, Object> map2 = new HashMap<>();
map2.put("id", 2);
map2.put("sku", "test2");
map2.put("quantity", 2);
Map<String, Object> map3 = new HashMap<>();
map3.put("id", 3);
map3.put("sku", "test3");
map3.put("quantity", 3);
ArrayList<Map<String, Object>> arrayList = new ArrayList<>();
arrayList.add(map1);
arrayList.add(map2);
arrayList.add(map3);
printArrayList(arrayList);
}
public static void printArrayList(ArrayList<Map<String, Object>> arrayList) {
for (Map<String, Object> entry : arrayList) {
for (String key : entry.keySet()) {
String value = entry.get(key).toString();
System.out.println(key + " : " + value);
}
System.out.println("-----------");
}
}
}
Your iterator for the arrayList is correct. To retrieve a value from a map, simply provide the key into the 'get' function of the entry. Since your map has a "String" key to an "Object" value, you can use "toString()" on it to get the string from the Object returned from your key.
public static void printArrayList(ArrayList<Map<String, Object>> arrayList) {
for (Map<String, Object> entry : arrayList) {
String myID = entry.get("id").toString();
String mySKU = entry.get("sku").toString();
System.out.print("id:" + myID + " sku: " + mySKU);
System.out.println("-------------------");
}
}
user681574 seems to have already answered your problem, but I will just add one Java8 example code to do the same thing as you need, using streams
public static void printArrayList(ArrayList<Map<String, Object>> arrayList) {
arrayList.stream() //stream out of arraylist
.forEach(map -> map.entrySet().stream() //iterate through each map in the list, create stream out of maps' entryset
.filter(entry -> entry.getKey().equals("id") || entry.getKey().equals("sku")) //filter out only entries that we need (where key is "id" or "sku")
.forEach(idOrSku -> System.out.println(idOrSku.getKey() + ":" + idOrSku.getValue()))); //Iterate through the id/sku entries and print them out just as we want to
}

Selecting best data structure

Name - Code (String)
A - 123
B - 123
C - 23
D - 123
E - 23
F - 23
G - 66
H - 66
What's the best data structure to represent this data. Names should be able to iterate easily.
Edit
Names are unique.
What's needed to be done is something like this.
Had doubts in using Hashmap that why I asked.
Code is a STRING
for( loop dataStructure names (lets say n)){
if(NAME.equals(n){
String code = dataStructure.get(n);
do somthing
}
}
If the names are unique, a HashMap woulrd be apropriate.
You can iterate over the keys with keys().
To iterate over the entries you can iterate over the entrySet().
See the JavaDoc of Map
If you need to perform a reverse lookup you could use the BiMap from Guava. (General a very good library)
Map entries example:
public final class MapExample {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("A", "123");
for (Map.Entry<String, String> mapEntry : map.entrySet()) {
if (mapEntry.getKey().equals("A")) {
final String code = mapEntry.getValue();
System.out.println("Your desired code: " + code);
}
}
}
}
But since NAME seems to be a constant, you could simple do String code = map.get(NAME)?
I thinks you are considering this:
public enum Code {
A("123"),
B("123"),
C("23"),
D("123"),
E("23"),
F("23"),
G("66"),
H("66");
final public String value;
Code(String value) {
this.value = value;
}
}
String h = Code.H.value;
for (Code code : Code.values()) {
System.out.printf("Name %s, code %s%n", code, code.value);
}
Sounds like a Map. Specifically, if the order of the names is important, you can use a TreeMap.
You can populate it with the put method, and then iterate over the entries (or just the keys, or just the values):
// Fill the map:
Map<String, String> map = new TreeMap<>();
map.put("A", "123");
map.put("B", "123");
// etc...
// Iterate over it:
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.pritnln ("Key: " + entry.getKey() + " value: " + entry.getValue());
}
EDIT:
If the order is not important, as noted in later edits to the OP, a HashMap would do just fine.
Note, however, that if you're looking for a specific key, like stated in the example in the OP, there's no point in looping over the keys - you just need to use get or containsKey:
String name = ...;
String code = map.get(name);
if (code != null) {
// do something...
}
I would suggest go for HashMap
The HashMap class uses a hashtable to implement the Map interface.
This allows the execution time of basic operations, such as get( )
and put( ), to remain constant even for large sets
HashMap are efficient for locating a value based on a key and
inserting and deleting values based on a key. The entries of a
HashMap are not ordered.
import java.util.HashMap;
import java.util.Set;
public class MyHashMapRead {
public static void main(String a[]){
HashMap<String, Integer> hm = new HashMap<String, Integer>();
//add key-value pair to hashmap
hm.put("A", "1");
hm.put("B", "2");
hm.put("C","3");
System.out.println(hm);
Set<String> keys = hm.keySet();
for(String key: keys){
System.out.println("Value of "+key+" is: "+hm.get(key));
}
}
}

Java HashMap key value storage and retrieval

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));
}
}
}

Categories