HashMap return the lasted record if it has multiple records with the same key, but different value - hashmap

I have the following map..
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put(1,"tom");
hmap.put(1,"jerry");
hmap.put(1,"Jeff");
System.out.println(hmap.get(1));
The output is "Jeff"
Why it always returns the latest record?

An HashMap, store items in "key/value" pairs. The key is unique inside a Map. So when you are doing a put on an existing key, you are overwriting the value, you lost the previous one. Thus, always the latest inserted record is returned.
You can check this link https://www.w3schools.com/java/java_hashmap.asp or the official doc at https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html

Related

Delete element in the middle of mapping

I need to delete an item in the middle of the Everscale solidity mapping containing struct:
struct Example {
string data;
uint64 validFrom;
uint64 valiUntil;
}
mapping(uint64 => Example) example;
example[1668161798] = Example("Start", 1668161798, 1668162798);
...
example[1668163798] = Example("Middle", 1668163798, 1668164798); // <-- Need to delete this one
...
example[1668165798] = Example("End", 1668165798, 1668166798);
Question 1
What is the best way to do this in terms of:
Gas consumption?
Storage?
Is it using the delete instruction work from the Ethereum example, or is it better to rebuild and reassign the mapping?
delete example[1668163798];
Question 2
What happens to the data contained in the mapping's item after using delete? Is there any garbage collector that wipes them out to minimize the storage?
What will happen if I reassign new data on the same index after deletion?
delete example[1668163798];
is the right way to do it. "delete" assigns the default value of the type for the variable it is applied to. For the mapping key, it removes the pair from the dictionary, thus freeing the storage space.
assigning a new value to the previously deleted key is no different from adding any other (key, value) pair to the dictionary; it works just fine.

Map to hold multiple sets of key and values

I have a map1 which holds the information as
[40256942,6] [60246792,5]
Now that I want to prepare a map2 that holds information such as
itemNo, 40256942
qty, 6
itemNo, 60246792
qty, 5
to prepare final information as json
“partialArticlesInfo”: [{itemNo:”40256942”, availQty:”6”}, {itemNo:”60246792”, availQty:”5”}]
I am trying to iterate map1 to retrieve values and set that against the key. But I am getting only one entry which is last one. Is there any way , I get the new map with entries such as mentioned above
Map<String, String> partialArticlesInfo = new HashMap<String,String>();
Map<String, String> partialArticlesTempMap = null;
for (Map.Entry<String,String> entry : partialStockArticlesQtyMap.entrySet())
{
partialArticlesTempMap = new HashMap<String,String>();
partialArticlesTempMap.put("itemNo",entry.getKey());
partialArticlesTempMap.put("availQty",entry.getValue());
partialArticlesInfo.putAll(partialArticlesTempMap);
}
In Java (I'm assuming you're using Java, in the future it would be helpful to specify that) and every other language I know of, a map holds mappings between keys and values. Only one mapping is allowed per key. In your "map2", the keys are "itemNo" and "availQty". So what is happening is that your for loop sets the values for the first entry, and then is overwriting them with the data from the second entry, which is why that is the only one you see. Look at Java - Map and Map - Java 8 for more info.
I don't understand why you are trying to put the data into a map, you could just put it straight into JSON with something like this:
JSONArray partialArticlesInfo = new JSONArray();
for (Map.Entry<String,String> entry : partialStockArticlesQtyMap.entrySet()) {
JSONObject stockEntry = new JSONObject();
stockEntry.put("itemNo", entry.getKey());
stockEntry.put("availQty", entry.getValue());
partialArticlesInfo.put(stockEntry);
}
JSONObject root = new JSONObject();
root.put("partialArticlesInfo",partialArticlesInfo);
This will take "map1" (partialStockArticlesQtyMap in your code) and create a JSON object exactly like your example - no need to have map2 as an intermediate step. It loops over each entry in map1, creates a JSON object representing it and adds it to a JSON array, which is finally added to a root JSON object as "partialArticlesInfo".
The exact code may be slightly different depending on which JSON library you are using - check the docs for the specifics.
I agree with Brendan. Another solution would be otherwise to store in the Set or List objects like the following.
class Item {
Long itemNo;
int quantity;
public int hashCode() {
Long.hashCode(itemNo) + Integer.hashCode(quantity);
}
public int equals(Object other) {
other instanceOf Item && other.itemNo == this.itemNo && other.quantity = this.quantity;
}
}
}
then you can use the JsonArray method described by him to get the Json string in output
This means that adding new variables to the object won't require any more effort to generate the Json

deleting key,value pairs from a dictionary given a list of keys to delete

I have a List<string> AllowedList and a Dictionary<string,List<string>> MyDictionary.
For each key in the dictionary, I want to check if it's on the AllowedList, if not I want to delete the key and value from the dictionary.
I intuitively tried this which seems to be what I wanted:
foreach (string key in MyDictionary.Keys)
{
if (!AllowedList.Contains(key)) MyDictionary.Remove(key);
}
However, I encountered an InvalidOperationException:
Collection was modified; enumeration operation may not execute.
I'm sure there's probably a simple way around this, but I don't immediately see it.
You could use Enumerable.Except to find the keys that are not in the dictionary:
foreach (var key in MyDictionary.Keys.Except(AllowedList).ToList())
MyDictionary.Remove(key);
The ToList() creates a new list of the set difference and prevents the exception.
You could/should store the keys you want to delete in a temporary list and do all the removing in an extra for-loop after that.
List<TKey> templist = new List<TKey>();
foreach (var x in MyDictionary)
{
if (!AllowedList.Contains(x.Key))
templist .Add(x.Key);
}
foreach (TKey item in templist )
{
MyDictionary.Remove(item);
}
this could also be helpful:
How to delete entries from a dictionary using the value

How to set record id by myself in J2ME

I use RecordStore to store my data.
I know when we store data in RecordStore, it automatically generates a record id for each record.
But how can I set the record id by myself? Or how can I get the record id?
Because I want to use the recordstore.setRecord(..) method to update my recordstore.
But when I use RecordEnumeration to fetch RecordStore and use method nextRecordId(), it just shows odd or even ids. I mean when I have 8 records, it just prints out only odd or even records like
2 4 6 8
My code:
handleRecord.openRecordStore(handleRecord.getRecordName());
RecordEnumeration re;
try {
int rc = handleRecord.getRecordStore().getNumRecords();
re = hrs.getRcs().enumerateRecords(null, null, true);
while(re.hasNextElement()) {
int rid = re.nextRecordId();
System.out.println(rid);
}
} catch(Exception e) {
System.out.println(e.toString());
}
MIDP API doesn't have method to set record id by yourself.
See RecordStore API documentation for explanation how this is supposed to work.
"Records are uniquely identified within a given record store by their recordId, which is an integer value. This recordId is used as the primary key for the records. The first record created in a record store will have recordId equal to one (1). Each subsequent record added to a RecordStore will be assigned a recordId one greater than the record added before it. That is, if two records are added to a record store, and the first has a recordId of 'n', the next will have a recordId of 'n + 1'..."
The code that iterates the store appears OK:
re = hrs.getRcs().enumerateRecords(null, null, true);
while(re.hasNextElement()) {
int rid = re.nextRecordId();
System.out.println(rid);
}
if you're getting only odd or even record like 2-4-6... or 1-3-5... printed as a result, first thing to check is whether you somehow removed records that are "missing" - this could be done eg using RecordStore.getVersion method:
"Each time a record store is modified (by addRecord, setRecord, or deleteRecord methods) its version is incremented. This can be used by MIDlets to quickly tell if anything has been modified..."

Can Automapper map from a Dictionary of properties to a flat destination?

Source contains a property bag in a Dictionary. Can Automapper map the entries in the Dictionary to individual properties of the Destination based upon matching the dictionary keys with the names of the properties on the destination type?
Example:
public class Destination
{
public int ProdNumber;
public string Title;
}
public class Source
{
public Dictionary<string, object> values = new Dictionary<string, object>();
}
where the values Dictionary will have two entries, one with a key of "ProdNumber" and one with a key value of "Title". There will likely be entries in the dictionary that have keys that don't match any property in the Destination and they should be ignored. There will be multiple properties of each primitive data type (int, string, etc) - so I presume I can't use a simple set of TypeConverters.
Any suggestions?
Thanks,
Chris
Unfortunately it is not possible at the moment, but it is planned for the next version. Read this thread as it discusses the plans and a work around.

Resources