Reputation: 1868
I am storing a data in HashMap and getting the value in later stage.
HashMap<String, byte[]> hm = new HashMap<String, byte[]>();
Now, I want to store two more values into it. For example, I want to store info like below. Could someone please advise me, how can i modify the Hashmap to ahieve this way? I also require to read all these stored values and find some value from it in later stage.
Key 1
IPAddress
RandomNumber
Byte data
Key 2
IPAddress
RandomNumber
Byte data
Thank you!
Upvotes: 0
Views: 2212
Reputation: 22506
You have to create a class with these properties:
class MyData{
private String IPAddress;
private long RandomNumber;
private byte[] data;
//getters setters...
}
Map<String, MyData> hm = new HashMap<String, MyData>();
You can get the values as:
MyData dataObj = hm.get("Key 1");
dataObj.getRandomNumber();
or directly
hm.get("Key 1").getData();
hm.get("Key 1").getRandomNumber();
To iterate over the map:
Iterator it = hm.entrySet().iterator();
while (it.hasNext()) {
Map.Entry myDataEntry = (Map.Entry)it.next();
System.out.println(myDataEntry.getKey() + " = " + myDataEntry.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
Taken from here: Iterate through a HashMap
Upvotes: 2
Reputation: 5067
I see two options for your issue:
1 - make a bean to wrap all the needed content (as advised by other posters)
2 - if you want to have more values for a single key and adding a new library to your project is not an issue you can use google guava library, more particularly the Multimap class. There you can have more values for a single key.
Nevertheless I would advise in writing a java bean that wraps the content you want in a single object.
Upvotes: 0
Reputation: 3807
Create a class like:
public class Key{
int randomNumber;
byte[] data;
String ipAddress;
}
And store it like a value of your Map.
Map<String, Key> map;
Hope it helps.
Upvotes: 0