Store multiple values in HashMap and get it later - java

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!

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

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.

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.

Related

How to use HashMap when Json file has same key value

My json file looks like this [actually it has more, I am just putting 2 blocks for example]
[{
"answerValue": "2021-02-01",
"parentId": "Policy",
"instance": 1,
"fieldId": "PolicyEffectiveDate"
},
{
"answerValue": "2012",
"parentId": "Insured",
"instance": 1,
"fieldId": "DateBusinessStarted"
}
]
I want to store them in a HashMap and print them.
public void MapCheck() {
Map<String, Object> dataMap = new HashMap<>();
List<Map> lstMap = new ArrayList<>();
dataMap.put("answerValue:", "2021-02-01");
dataMap.put("parentId:", "Policy");
dataMap.put("instance:", 1);
dataMap.put("fieldId:", "PolicyEffectiveDate");
lstMap.add(dataMap);
dataMap.put("answerValue:", "Assurestart LLC");
dataMap.put("parentId:", "Insured");
dataMap.put("instance:", 1);
dataMap.put("fieldId:", "Business_Name");
lstMap.add(dataMap);
System.out.println(lstMap);
}
public static void main(String[] args) {
Test t = new Test();
t.MapCheck();
}
}
Expected: I wanted it to print
[{parentId:=Policy, fieldId:=PolicyEffectiveDate, answerValue:=2021-02-01, instance:=1}, {parentId:=Insured, fieldId:=Business_Name, answerValue:=Assurestart LLC, instance:=1}]
Actual: It is printing, the last value twice.
[{parentId:=Insured, fieldId:=Business_Name, answerValue:=Assurestart LLC, instance:=1}, {parentId:=Insured, fieldId:=Business_Name, answerValue:=Assurestart LLC, instance:=1}]
How can I make it print 2 different values? Thanks in advance for your time and ideas.
You should create a new map for the second entry instead of overwriting the first entry’s values. Add
dataMap = new HashMap<>();
After adding the first entry to the list.
You should create a new map for the second map in the list:
Map<String, Object> dataMap = new HashMap<>();
List<Map<String, Object>> lstMap = new ArrayList<>();
dataMap.put("answerValue:", "2021-02-01");
dataMap.put("parentId:", "Policy");
dataMap.put("instance:", 1);
dataMap.put("fieldId:", "PolicyEffectiveDate");
lstMap.add(dataMap);
dataMap = new HashMap<>(); // create a new map!
dataMap.put("answerValue:", "Assurestart LLC");
dataMap.put("parentId:", "Insured");
dataMap.put("instance:", 1);
dataMap.put("fieldId:", "Business_Name");
lstMap.add(dataMap);
That said, if you actually want to generate JSON, or read a JSON file, I recommend using a JSON serialisation/deserialisation library, such as GSON. That way, you can represent your data not as hash maps, but a class like this:
class MyObject {
private String answerValue;
private String parentId;
private int instance;
private String fieldId;
// getters & setters...
}
HashMap as you know is a data structure that works based on unique key and value pair property.
In the example above when you perform dataMap.put("answerValue:", "2021-02-01"); it saves the value for this key in the HashMap. However when you perform, dataMap.put("answerValue:", "Assurestart LLC"); the second time, it will override the value of "answerValue:" key as it already exists there.
A better approach is to create a new class that can contain all this data in it and then you can decide on a unique key to store this data in. Thus your values will be an object that contains this entire block of data.
For example,
public class MyData {
private String answerValue;
private String parentId;
private Integer instance;
private String fieldId;
//Setters and getters
...
}

Best approach to have multiple key-value pairs, in a Value of an outer key

I am trying to create a dictionary type record, that holds for example key="Book name" and value= (key="price": $250, key="qty": 10). What would be the easiest way to achieve this is Java ? I have tried by creating a separate class object for they Value.
public class book_info {
int price = 0;
int qty = 0;
public void book_info(int qty, int price){
this.qty = qty;
this.price = price;
}
}
and creating a HashMap instance;
Map <String, book_info> items = new HashMap<String, book_info>();
items.put("Book1", new book_info(600, 20));
items.put("Book2", new book_info(200, 30));
items.put("Book3", new book_info(100, 50));
This works fine but is there any other alternate way by NOT using a separate class object, instead by just adding multiple key-value pairs in the initialization of HashMap like this;
Map <String, <<String, Integer>,<String, Integer>>> items = new HashMap<String, <<String, Integer>,<String, Integer>>>();
your question was probably already been answered, what your trying to do is use an object as the maping key, so instead of having [key, object] you want to have [object1, object2] and each object can be a map of which at the end will make them [[key1, value1][key2, value2]] for more details on using objects as keys see answer:
Using an instance of an object as a key in hashmap, and then access it with exactly new object?

Selecting certain data from ArrayList

I wondering if there is anyway that if I know one part of an ArryList that I can find out the other. The problem I'm running into is my limited knowledge of java.
I have the list set up as:
spotsList = new ArrayList<HashMap<String, String>>();
The activity goes through and adds every spot(from a server) to the list in a forloop with PID and NAME as:
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
spotsList.add(map);
Now is there a way I can get the name if I know the PID?
Thank you in advance,
Tyler
It seems that you expect the PIDs to be unique (given a PID you can find the corresponding name). So instead of a list of maps you should probably just use one map:
Map<String, String> map = new HashMap<String, String>();
for (Spot s : spots) map.put(s.id, s.name);
Retrieving a name from the pid is then simply a matter of:
String name = map.get(pid);
You should probably use a domain class instead of a HashMap to hold that data. If you did that you could easily search a collection for a particular value.
public class Spot {
private final String pid;
private final String name;
public Spot(String pid, String name) {
this.pid = pid;
this.name = name;
}
// getters
}
You'll want to add override equals() and hashCode() also.
And then use a map instead of a list:
Map<String,Spot> spots = new HashMap<String,Spot>();
spots.put(pid, new Spot(pid, name));
Then to find one:
Spot spot = spots.get(pid);

Getting values in hash map in Java

I am not a java developer, and this is not my homework or something. I am just in need of getting the values of these parameters: end & begin. this is what I have:
rs = [{}, {end=2013/11/5, begin=2012/11/6}]
I am wonder if I could get values like this:
rs[1].end
rs[1].begin
the source is:
protected QueryParameters prepareForm(final ActionContext context) {
final SearchErrorLogForm form = context.getForm();
Map<String, Object> rs = form.getValues();
System.out.println(rs);
/*the output is: {pageParameters={}, period={end=2013/11/5, begin=2013/11/6}} */
}
sorry, the rs type is hashmap.
That is not a valid statement.
A proper way of assigning an array would be:
String dates[] = {"2013/11/5","2012/11/6"};
String start = dates[0];
String end = dates[1];
There is a excellent tutourial at oracle docs
Okay, that is a Map containing two Maps as it seems. The first map named "pageParameters" is empty. The second one is named period and contains two items. The key "end" maps to the value "2013/11/5". The key "begin" maps to the value "2013/11/6".
To access the objects in the map you could do like this:
final Map<String, String> period = (Map<String, String>) rs.get("period");
final String begin = period.get("begin");
final String end = period.get("end");
If you would like to change a value in the map period you will need to overwrite the already existing one:
period.put("end", "NEW_END");
rs.put("period", period);
For further information, Oracle has great tutorials on Hashmaps.
you can do like following:
rs[1][0] for the first
rs[1][rs[1].length-1] for the last

Changing LinkedHashMapValues

Below is data from 2 linkedHashMaps:
valueMap: { y=9.0, c=2.0, m=3.0, x=2.0}
formulaMap: { y=null, ==null, m=null, *=null, x=null, +=null, c=null, -=null, (=null, )=null, /=null}
What I want to do is input the the values from the first map into the corresponding positions in the second map. Both maps take String,Double as parameters.
Here is my attempt so far:
for(Map.Entry<String,Double> entryNumber: valueMap.entrySet()){
double doubleOfValueMap = entryNumber.getValue();
for(String StringFromValueMap: strArray){
for(Map.Entry<String,Double> entryFormula: formulaMap.entrySet()){
String StringFromFormulaMap = entryFormula.toString();
if(StringFromFormulaMap.contains(StringFromValueMap)){
entryFormula.setValue(doubleOfValueMap);
}
}
}
}
The problem with doing this is that it will set all of the values i.e. y,m,x,c to the value of the last double. Iterating through the values won't work either as the values are normally in a different order those in the formulaMap. Ideally what I need is to say is if the string in formulaMap is the same as the string in valueMap, set the value in formulaMap to the same value as in valueMap.
Let me know if you have any ideas as to what I can do?
This is quite simple:
formulaMap.putAll(valueMap);
If your value map contains key which are not contained in formulaMap, and you don't want to alter the original, do:
final Map<String, Double> map = new LinkedHashMap<String, Double>(valueMap);
map.keySet().retainAll(formulaMap.keySet());
formulaMap.putAll(map);
Edit due to comment It appears the problem was not at all what I thought, so here goes:
// The result map
for (final String key: formulaMap.keySet()) {
map.put(formulaMap.get(key), valueMap.get(key));
// Either return the new map, or do:
valueMap.clear();
valueMap.putAll(map);
for(Map.Entry<String,Double> valueFormula: valueMap.entrySet()){
formulaMap.put(valueFormula.getKey(), valueFormula.value());
}

Categories

Resources