I need to create a hashmap with key as integer and it should hold multiple values of different data types. For example if the key is msg id and the values are
Then how to store the values of different data type with a single key into the hashmap?
Yep Sure.. please find the edited answer.. The example is only all about how to add,search, retrieve values in HashMap.
Overview. A HashMap stores key-value mappings. In this tutorial, we'll discuss how to store values of different types in a HashMap.
HashMap 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.
HashMap is a collection to store (key,value) pairs and According to the documentation of HashMap the keys are always unique. If you add a key which already exists(collision) in the hashmap, the old value will be replaced.
If you don't have Your own Data Class, then you can design your map as follows
Map<Integer, Object> map=new HashMap<Integer, Object>();
Here don't forget to use "instanceof" operator while retrieving the values from MAP.
If you have your own Data class then then you can design your map as follows
Map<Integer, YourClassName> map=new HashMap<Integer, YourClassName>();
import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Set; public class HashMapTest { public static void main(String[] args) { Map<Integer,Demo> map=new HashMap<Integer, Demo>(); Demo d1= new Demo(1,"hi",new Date(),1,1); Demo d2= new Demo(2,"this",new Date(),2,1); Demo d3= new Demo(3,"is",new Date(),3,1); Demo d4= new Demo(4,"mytest",new Date(),4,1); //adding values to map map.put(d1.getKey(), d1); map.put(d2.getKey(), d2); map.put(d3.getKey(), d3); map.put(d4.getKey(), d4); //retrieving values from map Set<Integer> keySet= map.keySet(); for(int i:keySet){ System.out.println(map.get(i)); } //searching key on map System.out.println(map.containsKey(d1.getKey())); //searching value on map System.out.println(map.containsValue(d1)); } } class Demo{ private int key; private String message; private Date time; private int count; private int version; public Demo(int key,String message, Date time, int count, int version){ this.key=key; this.message = message; this.time = time; this.count = count; this.version = version; } public String getMessage() { return message; } public Date getTime() { return time; } public int getCount() { return count; } public int getVersion() { return version; } public int getKey() { return key; } @Override public String toString() { return "Demo [message=" + message + ", time=" + time + ", count=" + count + ", version=" + version + "]"; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With