Add new line to list if key already exist - java

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(...);

Related

LinkedHashMap with values as a vector being overwritten

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

Arraylist element name already exists, update otherwise create new one in java

I have trying to get the string value from the arraylist values.
But In my arraylist if the value already exists , just update the count . otherwise need to create a new one. Here values are updating, but how can i create a new one element if the name didn't match with the arraylist element name? Please tell me , how can i verify the element(GlobalData.getCRole) already exists in the arraylist.
In this code the arraylist name is GlobalData.getrolecount
GlobalData.getCRole = item.getRole_name();
if (GlobalData.getrolecount.size() > 0) {
for (int i = 0; i < GlobalData.getrolecount.size(); i++) {
Role getrc = GlobalData.getrolecount.get(i);
Role getrcverify = new Role();
getrcverify.setRole_name(GlobalData.getCRole);
if (getrc.getRole_name().equalsIgnoreCase(GlobalData.getCRole)) {
String inccount = GlobalData.getrolecount.get(i).getCount();
int getcount = Integer.parseInt(inccount) + 1;
getrc.setCount(Integer.toString(getcount));
}
}
} else {
Role getrc = new Role();
getrc.setRole_name(GlobalData.getCRole);
getrc.setCount("1");
GlobalData.getrolecount.add(getrc);
}
Adding to #GabeSechan's answer, here's a snippet that would help you:
//let's say you store your data in a Map called myHashMap
String keyToMatch = "your_key_here"; // replace this line with whatever code you use to get your key
if(myHashMap.containsKey(keyToMatch)) // Check if your map already contains the key
{
int val = myHashMap.get(keyToMatch);
myHashMap.put(keyToMatch, val++); // Can be shrunken to a single line
}
else
{
myHashMap.put(keyToMatch, 1); // If it doesn't exist in the map, add it (with count 1)
}
This code can be shrunken much more because Map<> is a very robust tool. But I've written it in a way similar to your implementation so you can understand it better.
Let me know if you need further explanation or help trying to init myHashMap.
I'd use a different data structure. A list isn't what you want. You want a Map (probably a HashMap) of strings to Count, or of strings to Roles. That way you can do O(1) searches to see if a role already exists, rather than an O(n) walk of the list, and checking if the role exists is a simple check to see if get returns null.

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.

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

Hash how to push new and update current

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);

Categories

Resources