Hash how to push new and update current - java

I have Hash like
private Map<String, List<MEventDto>> mEventsMap;
Then I want to check if the key already exist. If it exist, I will just update the values and I will add a new key. How can I do this.
I try like:
for (MEventDto mEventDto : mEventList) {
String mEventKey = mEventDto.getMEventKey();
String findBaseMEvent = mEventKey.split("_")[0];
if (mEventsMap.get(findBaseMEvent ) != null) {
// create new one
mEventsMap.put(findBaseMEvent , mEventDtoList);
} else {
// just update it
mediationEventsMap.
}
}
How can I do this with Hash?

You can use Map#containsKey to check whether a key is present or not: -
So, in your case, it would be like this: -
if (mEventsMap.containsKey(findBaseMEvent)) {
// just update the enclosed list
mEventsMap.get(findBaseMEvent).add("Whatever you want");
} else {
// create new entry
mEventsMap.put(findBaseMEvent , mEventDtoList);
}

HashMap containsKey() You can use this method
boolean containsKey(Object key)
Returns true if this map contains a mapping for the specified key.

You would do it as follows:
String mEventKey = mEventDto.getMEventKey();
String findBaseMEvent = mEventKey.split("_")[0];
List<MEventDto> list = mEventsMap.get(findBaseMEvent);
/*
* If the key is not already present, create new list,
* otherwise use the list corresponding to the key.
*/
list = (list == null) ? new ArrayList<MEventDto>() : list;
// Add the current Dto to the list and put it in the map.
list.add(mEventDto);
mEventsMap.put(findBaseMEvent , mEventDtoList);

Related

Removing Keys from hashmap thru composite key value

Hey guys currently have problem with regards to removing duplicates from hashmap.
Some background:
My hashmap is in this format Map<CompositeKeyBean,ValueBean>.
CompositeKeyBean is in the form (String ID, String hashvalue);
ValueBean is an object.
So if i have a hashmap with values as such:
(ID:1,HashValue:123),Obj1
(ID:1,HashValue:234),Obj1
(ID:1,HashValue:345),Obj1
I need to remove the duplicate keys and only have items with unique IDs. currently I have come up with this, But it does not seem to work, im pretty sure i am doing something wrong.
for (Map.Entry<CompositeKeyBean, ReportDataBean> entry : list.entrySet())
{
String idvalue = entry.getKey().getCompositeKeyList().get(0);
for(int i = 1; i < list.size();i++)
{
if(list.keySet().contains(idvalue))
{
list.remove(i);
}
}
}
My solution for this one would be to declare first an another Map which will be used to hold the number of times that a certain key has appeared in the original Map. For the second time, you can iterate the same map entrySet and remove the duplicates using the declared additional Map as reference.
Map<String, Integer> numberOfInstanceMap = new HashMap<String, Integer>(); //temporary placeholder
for (Map.Entry<CompositeKeyBean, ReportDataBean> entry : list.entrySet())
{
String idvalue = entry.getKey().getCompositeKeyList().get(0);
if(!numberOfInstanceMap.containsKey(idvalue)) {
numberOfInstanceMap.put(idvalue, 1); //initialize the key to 1
} else {
numberOfInstanceMap.replace(idValue, numberOfInstanceMap.get(idValue) + 1); //add 1 to the existing value of the key
}
}
for (Map.Entry<CompositeKeyBean, ReportDataBean> entry : list.entrySet())
{
String idvalue = entry.getKey().getCompositeKeyList().get(0);
Integer i = numberOfInstanceMap.get(idValue);
if(i>1) { //remove duplicate if the key exists more than once
list.remove(idValue);
}
}
If you are expecting duplicate keys, then you can do the following way to handle it while populating the map itself:
Map<String, String> map = new HashMap<>();
if(map.containsKey("ID")){
String oldValue = map.get("ID");
//put logic to merge the value
}else{
map.put("ID","newValue");
}

How can I add a string one at a time to a HashMap<Integer, List<String>>?

This function loops through a dictionary (allWords) and uses the
getKey function to generate a key. wordListMap is a HashMap> so I need to loop through and put the key and and a List. If there is not a list I put one if there is I just need to append the next dictionary word. This is where I need help. I just can't figure out the syntax to simply append the next word to the list that is already there. Any Help would be appreciated.
public static void constructWordListMap() {
wordListMap = new HashMap<>();
for (String w : allWords) {
int key = getKey(w);
if (isValidWord(w) && !wordListMap.containsKey(key)) {
List list = new ArrayList();
list.add(w);
wordListMap.put(key, list);
} else if (isValidWord(w) && wordListMap.containsKey(key)) {
wordListMap.put(key, wordListMap.get(key).add(w));
}
}
}
map.get(key).add(value)
Simple as that.
So I've gathered that you want to, given HashMap<Integer, List<String>>, you'd like to:
create a List object
add String objects to said List
add that List object as a value to be paired with a previously generated key (type Integer)
To do so, you'd want to first generate the key
Integer myKey = getKey(w);
Then, you'd enter a loop and add to a List object
List<String> myList = new List<String>;
for(int i = 0; i < intendedListLength; i++) {
String myEntry = //wherever you get your string from
myList.add(myEntry);
}
Lastly, you'd add the List to the HashMap
myHash.put(myKey, myList);
Leave any questions in the comments.
else if (isValidWord(w) && wordListMap.containsKey(key)) {
wordListMap.put(key, wordListMap.get(key).add(w));
}
If you want to add a new value to your list, you need to retrieve that list first. In the code above, you are putting the return value of add into the table (which is a boolean), and that is not what you want.
Instead, you will want to do as Paul said:
else if (isValidWord(w) && wordListMap.containsKey(key)) {
wordListMap.get(key).add(w);
}
The reason this works is because you already added an ArrayList to the table earlier. Here, you are getting that ArrayList, and adding a new value to it.

prepare a multi valued country map

I want to prepare a HashMap in such way that
Key : Country Code
Value : List of returned orderEntries
the following process data method process every 5 orderEntry which can be from any country.
let me make it more clear. I have list of orderEntries that come from different countries now I want to put these entries into map based on country key. Like if 20 entries coming from US then US will be the key and 20 Entries would be the values. But problem is that I don't want to create a list for each county inside map.
public void processSegmentData(final List resultSet)
{
for (final Object orderEntry : resultSet)
{
if (orderEntry instanceof OrderEntryModel)
{
String countryCode = null;
final OrderModel order = ((OrderEntryModel) orderEntry).getOrder();
if (order.getDeliveryAddress() != null)
{
countryCode = order.getDeliveryAddress().getCountry().getIsocode();
}
orderEntriesMap.put(Config.getParameter(countryCode+".return.pid"), orderEntries);
}
}
}
so you are after a hashmap which contains a linked list Something along the lines of:
public HashMap<String, LinkedList<OrderEntryModel>> processSegmentData(final List resultSet) {
HashMap<String, LinkedList<OrderEntryModel>> orderEntriesMap = new HashMap<String, LinkedList<OrderEntryModel>>();
for (final Object orderEntry : resultSet) {
if (orderEntry instanceof OrderEntryModel) {
String countryCode = null;
final OrderModel order = ((OrderEntryModel) orderEntry).getOrder();
if (order.getDeliveryAddress() != null) {
countryCode = order.getDeliveryAddress().getCountry().getIsocode();
}
if (!orderEntriesMap.containsKey(countryCode)) {
orderEntriesMap.put(countryCode, new LinkedList<OrderEntryModel>());
}
orderEntriesMap.get(countryCode).add((OrderEntryModel) orderEntry);
}
}
return orderEntriesMap;
}
would be an example based on the source code you provided guessing object names.
But problem is that I don't want to create a list for each county
inside map.
I understand your problem but map store unique key, you can not store same country code.
you have to use Map<String, List<String>>() that will hold your country code as key and then put your values inside List<String>.
after doing this if you have any problem edit your question will help you to resolve that.
Just Create a Map<String,List<String>>. and follow the following approach
Map<String,List<String>> countryMap = new HashMap<String, List<String>>();
for (final String orderEntry : orders){
if(countryMap.containsKey(orderEntry.getCountry())){
countryMap.get(orderEntry.getCountry()).add(orderEntry);
}else{
//create a new list and add orderEntry
countryMap.put(orderEntry.getCountry(),orderEntry);
}
}
You need to modify this according to your stuff
You could use Guava's Multimap to simplify things. A Multimap allows you to store multiple entries against a single key, e.g.:
Multimap<String, OrderEntry> orderEntriesMultimap = HashMultimap.create();
for (final Object orderEntry : resultSet) {
// omitted...
orderEntriesMultimap.put(Config.getParameter(countryCode+".return.pid"), orderEntry);
}
You can then retrieve all the associated values by key:
Collection<OrderEntryModel> entries = orderEntriesMultimap.get(key);

How to group some objects by certain field in Java?

I've been trying to group of facets by translated value, but what I always get is only one last object on the List (no dataset). Here is what I tried:
HashMap<String, List<Facet>> map = new HashMap<>();
for (Facet facet : getFacets()) {
map.put(facet.getTranslatedValue(), new ArrayList<com.schneider.gss.model.Facet>());
map.get(facet.getTranslatedValue()).add(facet);
}
Can you suggest anything?
Change your for loop as below
for (Facet facet : getFacets()) {
if(map.get(facet.getTranslatedValue()) == null) {
map.put(facet.getTranslatedValue(), new ArrayList<com.schneider.gss.model.Facet>());
}
map.get(facet.getTranslatedValue()).add(facet);
}
You're overwriting your list each time you get an identical translated value with a new ArrayList. Instead, you should check if it exists:
HashMap<String, List<Facet>> map = new HashMap<>();
for (Facet facet : getFacets()) {
//get the list
ArrayList<com.schneider.gss.model.Facet> list = map.get(facet.getTranslatedValue());
//if list doesn't exist, create it
if(list == null) {
map.put(facet.getTranslatedValue(), new ArrayList<com.schneider.gss.model.Facet>());
}
//then add to list
map.get(facet.getTranslatedValue()).add(facet);
}
in Guava there is class Multimap (or ArrayListMultimap) which does exactly what you need

Add new line to list if key already exist

I have to build hashMap that contain key object and list of instances that related to this key.
during the build of the map I want to ask if the key object(vocKey) already exist don't create new instance
for Voc key just add new line to the list of vocData ,how I can do that ?
private HashMap<vocKey,List<vocData>> vocabulary = new HashMap<vocKey,List<vocData>>();
See HashMap.get()
List<vocData> data = vocabulary.get(key);
if (data == null) {
vocabulary.put(...);
} else {
data.add(...);
}
This is just a guide. Give it a try yourself
1) First get the value using key.
2) if a value exist add new line to value list
3) if value does not exist create a new instance and add under new key.
List<vocData> data = vocabulary.get(key);
if (data == null) {
data = new ArrayList();
vocabulary.put(key, data);
}
data.add(...);

Categories

Resources