Title says it all but for the sake of example.. I'm currently learning Java now and as a personal experiment I'm writing a soft representation of an ATM screen.
I'm attempting to store three hash maps inside of one value within a list of arrays. Thus, giving me the ability to add multiple strings, all containing their own set of three maps.
So - I want an Array List for "User" and within this list, will be three maps for "Checking" "Saving" and "CDs".
When adding a new User, this user is also given the ability to add/modify/remove three different "accounts."
Thoughts?
See if it could help you solve the problem
HashMap <String,HashMap> holder = new HashMap<>();
HashMap <Integer,Integer> hm1 = new HashMap<>();
HashMap <Integer,String> hm2 = new HashMap<>();
hm1.put(0,10000000);
hm1.put(1,5000);
hm2.put(0,"xxxx-xxxx-xxxx");
hm2.put(1,"yyyy-yyyy-yyyy");
holder.put("Amt", hm1);
holder.put("Info", hm2);
Iterator<String> iterator = holder.keySet().iterator();
while(iterator.hasNext())
{String key = iterator.next();
System.out.println("key: " + key + " value: " + holder.get(key));
}
Output:
key: Amt value: {0=10000000, 1=5000}
key: Info value: {0=xxxx-xxxx-xxxx, 1=yyyy-yyyy-yyyy}
you can 1st fetch the desired field like Amt using the key1 and then use the key2 (0,1,2....)
for each person to fetch corresponding value.
Related
I have two linked hashmap (key - String, value = String[]) which got the same size and the same keys in both linked hashmaps, I want to be able to compare values according to the key, verifying values on one linked hashmap are equals to the same values in the second linked hashmap (by key) or at least the other linked hashmap contains the values.
I am populating both of the linked hashmaps with keys and values and set it to different linked hash maps.
Example for hashmap:
Key - alert - Value (array of strings)
0 - Device_UID,Instance_UID,Configuration_Set_ID,Alert_UID
1 - a4daeccb-0115-430c-b516-ab7edf314d35,0a7938aa-9a01-437f-88ac-4b2927ed7665,96,61b68069-9de7-4b85-83cb-8d9f558e8ecb
2 - a4daeccb-0115-430c-b516-ab7edf314d35,0a7938aa-9a01-437f-88ac-4b2927ed7665,12,92757faa-bf6b-4aa3-ba6d-2e57b44f333c
3 - a4daeccb-0115-430c-b516-ab7edf314d35,0a7938aa-9a01-437f-88ac-4b2927ed7665,369,779b3294-2ca3-4613-a413-bf8d4aa05d16
and it should be at least in the second linked hash- map
String rdsColumns="";
for(String key : mapServer.keySet()){
String[] value = mapServer.get(key);
String[] item = value[0].split(",");
rdsColumns="";
for(String val:item){
rdsColumns = rdsColumns.concat(val + ",");
}
rdsColumns = rdsColumns.concat(" ");
rdsColumns = rdsColumns.replace(", ", "");
info(("Query is: "+ returnSuitableQueryString(rdsColumns, key, alertId, deviceId)));
String query=returnSuitableQueryString(rdsColumns, key, alertId, deviceId);
mapRDS.put(key, insightSQL.returnResultsAsArray(query ,rdsColumns.split(","),rdsColumns));
}
where rdsColumns are the fields I am querying in RDS data-base.
Expected: iterating over both maps and verifying at that all values according to key in the first map contains or equal in the second map.
This is the code you are looking for:
for (String keys : firstMap.keySet()) {
String[] val1 = firstMap.get(keys);
String[] val2 = secondMap.get(keys);
if (Arrays.equals(val1, val2)) {
//return true;
}
ArrayList<Boolean> contains = new ArrayList<>();
for (int i = 0; i < val1.length; i++) {
for (String[] secondMapVal : secondMap.values()) {
List<String> list = Arrays.asList(secondMapVal);
if (list.contains(val1[i])) {
contains.add(true);
break;
} else contains.add(false);
}
}
if (contains.contains(true)) {
//return true; Even a single value matches up
} else {
//return false; Not even a sinle value matches up
}
}
Basically what we have here is a HashMap<String, String>. We take the set of keys and iterate through them. Then we take the value with the key from the two sets. After we got the values we compare them and if they are the same I just print that they match. You can change this and implement this with other types of HashMaps, even where you use custom values. If I didn't understand your problem tell me and I will edit the answer.
I have with me a List of Pairs which I insert into a LinkedHashMap and upload it to the Firestore document. However the key order in the Firestore Document does not match that of the LinkedHashMap.
Here's the code:
Map<String, String> quesMap = new LinkedHashMap<>();
for(Pair<String, String> pair : quesAnsPairList){
Log.d(TAG, "adding key : " + pair.first);
quesMap.put(pair.first, pair.second);
}
for (Map.Entry<String, String> entry : quesMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
Log.d(TAG, key + " found");
}
//....
visitorsCollectionRef.document(visitor_id).set(quesMap);
Unfortunately, you cannot change that order of documents. I see that you are using Strings when ordering. Note, that when strings are ordered, are ordered lexicographically.
Let's take a simple example. For numbers, this is the normal order:
1308
1309
1310
1311
But for strings, this is the normal order:
"1308"
"1309"
"131"
"1310"
There is no operator in Cloud Firestore and as far as i know nor in most other databases that allow you to change this behavior. Instead, you will have to modify the data to get the behavior you want. So, store values that are in the order you need them when sorted lexicographically. For numbers you can accomplish that by padding them with zeroes:
"0131" //zero added before
"0132" //zero added before
......
"1308"
"1309"
"1310"
"1311"
When I wrote this piece of code due to the pnValue.clear(); the output I was getting was null values for the keys. So I read somewhere that adding values of one map to the other is a mere reference to the original map and one has to use the clone() method to ensure the two maps are separate. Now the issue I am facing after cloning my map is that if I have multiple values for a particular key then they are being over written. E.g. The output I am expecting from processing a goldSentence is:
{PERSON = [James Fisher],ORGANIZATION=[American League, Chicago Bulls]}
but what I get is:
{PERSON = [James Fisher],ORGANIZATION=[Chicago Bulls]}
I wonder where I am going wrong considering I am declaring my values as a Vector<String>
for(WSDSentence goldSentence : goldSentences)
{
for (WSDElement word : goldSentence.getWsdElements()){
if (word.getPN()!=null){
if (word.getPN().equals("group")){
String newPNTag = word.getPN().replace("group", "organization");
pnValue.add(word.getToken().replaceAll("_", " "));
newPNValue = (Vector<String>) pnValue.clone();
annotationMap.put(newPNTag.toUpperCase(),newPNValue);
}
else{
pnValue.add(word.getToken().replaceAll("_", " "));
newPNValue = (Vector<String>) pnValue.clone();
annotationMap.put(word.getPN().toUpperCase(),newPNValue);
}
}
sentenceAnnotationMap = (LinkedHashMap<String, Vector<String>>) annotationMap.clone();
pnValue.clear();
}
EDITED CODE
Replaced Vector with List and removed cloning. However this still doesn't solve my problem. This takes me back to square one where my output is : {PERSON=[], ORGANIZATION=[]}
for(WSDSentence goldSentence : goldSentences)
{
for (WSDElement word : goldSentence.getWsdElements()){
if (word.getPN()!=null){
if (word.getPN().equals("group")){
String newPNTag = word.getPN().replace("group", "organization");
pnValue.add(word.getToken().replaceAll("_", " "));
newPNValue = (List<String>) pnValue;
annotationMap.put(newPNTag.toUpperCase(),newPNValue);
}
else{
pnValue.add(word.getToken().replaceAll("_", " "));
newPNValue = pnValue;
annotationMap.put(word.getPN().toUpperCase(),newPNValue);
}
}
sentenceAnnotationMap = annotationMap;
}
pnValue.clear();
You're trying a bunch of stuff without really thinking through the logic behind it. There's no need to clear or clone anything, you just need to manage separate lists for separate keys. Here's the basic process for each new value:
If the map contains our key, get the list and add our value
Otherwise, create a new list, add our value, and add the list to the map
You've left out most of your variable declarations, so I won't try to show you the exact solution, but here's the general formula:
List<String> list = map.get(key); // try to get the list
if (list == null) { // list doesn't exist?
list = new ArrayList<>(); // create an empty list
map.put(key, list); // insert it into the map
}
list.add(value); // update the list
I have a properties (cant change this file) and it looks like:
aaa.bbb.ccc.first=my first value
aaa.bbb.ccc.second=my second value
aaa.bbb.ccc.third=my third value
If I need any value in java classes I use i18n.getText("aaa.bbb.ccc.first") but it works only for single value.
Problem is because I dont know:
-value's names
-how many values are in aaa.bbb.ccc.~
How is it possible to get list of value aaa.bbb.ccc~?
You could use a MapFilter. Use the MapFilter(Properties p, String prefix) constructor.
public void test() {
Properties props = new Properties();
props.put("aaa.bbb.ccc.first", "my first value");
props.put("aaa.bbb.ccc.second", "my second value");
props.put("aaa.bbb.ccc.third", "my third value");
props.put("Other.props", "others");
MapFilter<String> filtered = new MapFilter(props, "aaa.bbb.ccc.");
for (Map.Entry<String, String> e : filtered.entrySet()) {
System.out.println("Key: " + e.getKey() + " Value: " + e.getValue());
}
System.out.println(filtered);
}
Hash maps are not meant for the kind of lookup you want to do: Tries and radix trees are. There is an implementation of the Patricia trie data structure (i.e., binary radix trees) in Apache Commons Collections: Just create a trie from your Map<String, Whatever> (you have a nice constructor at the purpose) and with prefixMap("aaa.bbb.ccc") you obtain the submap of all the entries whose key have that prefix.
Properties has a method propertyNames(). You can use that to get all the keys then do whatever you want from there.
I am trying to store data in a HashMap however I can only seem to store the very last item of the data source I am reading into the HashMap and I am unsure why.
Below is my code:
//Loops through the counties and stores the details in a Hashmap
void getCountyDetails(List<Marker>m){
HashMap t = new HashMap();
for(Marker county: countyMarkers){
println("county:" + county.getProperties());
t = county.getProperties();
}
println(t);
}
This line -> println("county:" + county.getProperties());
Outputs this:
county:{name=Carlow, pop=54,612}
county:{name=Cavan, pop=73,183}
county:{name=Clare, pop=117,196}
county:{name=Cork, pop=519,032}
county:{name=Donegal, pop=161,137}
county:{name=Dublin, pop=1,273,069}
county:{name=Galway, pop=250,541}
county:{name=Kerry, pop=145,502}
county:{name=Kildare, pop=210,312}
county:{name=Kilkenny, pop=95,419}
county:{name=Laois, pop=80,559}
county:{name=Letrim, pop=31,796}
county:{name=Limerick, pop=191,809}
county:{name=Longford, pop=39,000}
county:{name=Louth, pop=122,897}
county:{name=Mayo, pop=130,638}
county:{name=Meath, pop=184,135}
county:{name=Monaghan, pop=60,483}
county:{name=Offaly, pop=76,687}
county:{name=Roscommon, pop=64,065}
county:{name=Sligo, pop=65,393}
county:{name=Tipperary, pop=158,754}
county:{name=Waterford, pop=113,795}
county:{name=Westmeath, pop=86,164}
county:{name=Wexford, pop=145,320}
county:{name=Wicklow, pop=136,640}
I would like to store them in a HashMap.
This line -> println(t); outputs:
{name=Wicklow, pop=136,640}
Would appreciate any help on the matter guys. Basically it's just getting the list of data into the hashmap and currently only the last item in that list is being placed in.
If you want to print the properties of each Marker , move the println(t) line into the for loop, because at the moment t will point to the last used element's properties, because you just reassign it;s value each iteration of the cycle. To put an element in the map, use put(Key, Value) or putAll() methods instead
In java, you should use hashMap.put(key, value) to add new item into hash map.
In your code, you wrote HashMap t = new HashMap(); t = county.getProperties(); so you map value is actually been reassigned to country property each time.