How to add an item to list inner hashmap? - java

HashMap<String, List<Person.Personal>> hashMap = new HashMap();
var attachment = new Person.Personal(name, surname, birthDate);
I need to add item with key that comes from another map.
Then I need the code like below;
if(hashMap.containsKey(courseGroup.getKey().get(0)))
{
hashMap.put(courseGroup.getKey().get(0), attachment);
}
else
{
hashMap.put(courseGroup.getKey().get(0), new Arraylist<Person.Personal> (attachment));
}
This code show error:
Cannot resolve constructor 'Arraylist(Person.Personal)'
If the hashmap has the key then add its value list "attachment", if has not, create a list then add "attachment", I need.

if(hashMap.containsKey(courseGroup.getKey().get(0)))
{
hashMap.get(courseGroup.getKey().get(0)).add(attachment);
}
else
{
List<Person.Personal> list = new ArrayList<>();
list.add(attachment);
hashMap.put(courseGroup.getKey().get(0), list);
}
These lines solved my issue.

As the arraylist already exists instead of putting it again use updating the arraylist.
For example:
if(hashMap.containsKey(courseGroup.getKey().get(0)))
{
// adding values directly to the arraylist.
hashMap.get(courseGroup.getKey().get(0)).add(attachment);
}
else
{
List<Person.Personal> list= new Arraylist<> ();
list.add(attachment);
// create a new array and put it there.
hashMap.put(courseGroup.getKey().get(0), list);
}

Related

Adding value to list object in hash-map

I'm trying to add list object to hashmap
I tried with the following code didn't worked
public static Map<Long, List<Long>> getCellAttributes(List<Vo> voList){
LOG.info("VO: {}", Arrays.toString(VO.toArray()));
Map<Long, List<Long>> atributesMap = new HashMap();
List<Long> cellList = new ArrayList<>();
for(: VOList){
Long cID = VO.getID();
Long cellUserNumber = VO.getCellNumber();
if(cellMap.containsKey(ID)){
cellList.add(cellNumber);
cellmap.put(ID, list);
}
else {
Map.put(ID, cellAtributesMap.get(ID).add(cellNumber));
}
}
return cellMao;
}
Found below error for else block part.
Wrong 2nd argument type. Found: 'boolean', required:
Ok, first off, what is Map.put in the else block? To me it sounds wrong logically, probably you meant the case where the campaignId is not in the map yet.
In this case, you can just:
else {
List<Long> cellList = new ArrayList<>();
cellList.add(cellUserNumber);
cellAtributesMap.put(campaignId, cellList);
}
Now the if block also looks logically wrong, there is no need to maintain a global list (what if the targetedOffersCampaignVOList is not ordered) and there is no need to put every time into the map.
Since it doesn't seem to be a homework for me, here is a better version:
Map<Long, List<Long>> cellAtributesMap = new HashMap();
// note, the following line is not required and should be removed
//List<Long> cellList = new ArrayList<>();
for(TargetedOffersCampaignVO targetedOffersCampaignVO: targetedOffersCampaignVOList){
Long campaignId = targetedOffersCampaignVO.getCampaignID();
Long cellUserNumber = targetedOffersCampaignVO.getCellUserNumber();
if(cellAtributesMap.containsKey(campaignId)){
// the list in the value already exists anyway, just add a new cell user number to it
cellAttributesMap.get(campaignId).add(cellUserNumber);
}
else {
// create a new key-value pair in the result map
// and add one element which is a current cellUserNumber to it
List<Long> cellList = new ArrayList<>();
cellList.add(cellUserNumber);
cellAtributesMap.put(campaignId, cellList);
}
}
return cellAtributesMap;
I think you have problem in your else block:
else {
Map.put(campaignId, cellAtributesMap.get(campaignId).add(cellUserNumber));
}
Map call here is in inappropirate. If my guess is correct, you want to initialize a new array if that particular campaignId does not exist in previously, in that case you want to execute this else block. Then you just change your else block like this:
else
{
List<Long> newList= new ArrayList<>();
newList.add(cellUserNumber);
cellAtributesMap.put("campaignId", newList);
}
cellAtributesMap.get(campaignId).add(cellUserNumber)
Above method call returns a boolean value.
Your else block should be like below
List<Long> list=new ArrayList<>();//any list implementation
list.add(cellUserNumber);
cellAtributesMap.put(campaignId,list);

Method put() in java Map of type <<String>,List<String>>

How can I put in a map of above type. I do not want to overwrite existing mapping.
So far my code is:
public class Store {
Map<String, List<String>> items;
public Store(){
items = new HashMap<String, List<String>>();
}
public boolean containsKey(String key) {
return items.containsKey(key);
}
public void put(String key, String item) {
List<String> myList = new ArrayList<>();
if (myList == null) {
myList = new ArrayList<String>();
items.put(key, item);
}
}
}
I stopped here because I received an error message stating "change the item type to list String from String". I can not figure out if I am doing something wrong.
Here, double wrong:
List<String> myList = new ArrayList<>();
if (myList == null) {
myList = new ArrayList<String>();
items.put(key, item);
}
myList will never be null, you just assigned a list to it! And item is just a single string, so you shouldn't use it as value for a map that expects lists of strings as value!
You go:
List<String> myList = items.get(key);
if (myList == null) {
myList = new ArrayList<String>();
}
myList.add(item);
items.put(key, myList);
instead.
Meaning: first you check if you already have a list for that key. If not, you create an empty one. Then you add your new item to the (potentially new) list. Before finally putting the list into the map (it could be already there, but then you just overwrite that information with "itself").
And if you want to know how the "pros" solve this problem, have a look at this questions and the answers I received upon asking it.
Or use Map.computeIfAbsent() that is designed for this requirement : add a new entry if not existing mapping for a specific key and getting the value for (the new one or the existing) :
items.computeIfAbsent(key, k -> new ArrayList<>())
.add(item);

Update HashMap without adding new entry

My program uses two HashmMap and they have exactly the same number of entries and the same keys.
One (tableMap) is static and never changes. The other one is dynamic (partitionMap), this means that I need to update values.
My algorithm got a problem, because seems to be adding one more entry when it is supposed to be not.
//I have a LinkedList of strings that I want to add to the HashMap partitionMap
LinkedList<String> partition = new LinkedList<String>();
for (TerminalNode terminalNode : ctx.U()) {
partition.add(terminalNode.getText());
}
//for each entry of tableMap
for(Entry<String, LinkedList<String>> entry : tableMap.entrySet())
{
//I retrieve keys and values from tableMap
String key = entry.getKey();
LinkedList<String> attributes = entry.getValue();
//the condition: if my linkedlist is included in the other do...
if(attributes.containsAll(partition))
{
//get the list of values
ArrayList<LinkedList<String>> l = partitionMap.get(key);
//but the first time is always null since I init partitionMap without values
if(l==null)
{
ArrayList<LinkedList<String>> firstLL = new ArrayList<LinkedList<String>>();
firstLL.add(partition);
partitionMap.put(key, firstLL); //BUG HERE! add one more entry instead of just updating values
}
else
{
l.add(partition);
partitionMap.put(key, l);
}
}
}
Does anybody have an idea why this is wrong?

TreeMap using a string key and an arraylist

I am brand new to using collections, so I am confused on how to do this. I am trying to use a TreeMap to hold a word as the key and then an ArrayList to hold one or more definitions for the word.
public class Dict {
Map<String, ArrayList<String>> dic = new TreeMap<String, ArrayList<String>>();
public void AddCmd(String word, String def) {
System.out.println("Add Cmd " + word);
if(dic.get(word)==null){
dic.put(word, new ArrayList.add(def));
}
}
}
I am getting an error on "new ArrayList.add(def)". I thought this was the correct way to do this, but I am obviously wrong. Does anyone have any ideas as to what I am doing wrong?
Calling ArrayList#add returns a boolean which is not the desired value for your Map, thus getting the compiler error.
You need to insert the ArrayList and then add the element. Your code should look like this:
ArrayList<String> definitions = dic.get(word);
if (definitions == null) {
definitions = new ArrayList<String>();
dic.put(word, definitions);
}
definitions.add(def);
dic.put(word, new ArrayList.add(def)); is the culprit.
since you have declared map to take Arraylist of string as a value. the value to pass for map must be Arraylist of string.
but this line is adding a value as new ArrayList.add(def) since you are trying to create a list and adding element , add method returns boolean -> true if it can add false if it fails.
so it means value to the map is going as a boolean not as arraylist which is against the map declaration.
so use code as below
ArrayList<String> listOfString = dic.get(word);
if (listOfString == null) {
listOfString = new ArrayList<String>();
listOfString .add(def);
}
dic.put(word, listOfString );
You have to break it up, because add does not return the original ArrayList:
ArrayList<String>> NewList = new ArrayList<String>();
NewList.add(def);
dic.put(word, NewList);
You are not actually creating a new ArrayList. Try this:
ArrayList<String> newDef = new ArrayList<String();
newDef.add(def);
dic.put(word, newDef);

removing duplicates from list of lists and preserving lists

I have an arrayList of arrayLists. Each inner arraylist contains some objects with the format (name.version) .
{ {a.1,b.2,c.3} , {a.2,d.1,e.1} , {b.3,f.1,z.1}....}
For example a.1 implies name = a and version is 1.
So i want to eliminate duplicates in this arraylist of lists. For me , two objects are duplicate when they have the same name
So essentially my output should be
{ { a.1,b.2,c.3},{d.1,e.1} ,{f.1 ,z.1} }
Note that i want the output in the exact same form (That is , i dont want a single list with no duplicates)
Can someone provide me with an optimal solution for this?
I can loop through each inner list and place the contents in the hashset. But two issues there, i cant get back the answer in
form of list of lists.Another issue is that when i need to override equals for that object , but i am not sure if that would
break other code. These objects are meaningfully equal if their names are same (only in this case. I am not sure that would
cover the entire spectrum)
Thanks
I used Iterator.remove() to modify the collection as you move through it.
// build your example input as ArrayList<ArrayList<String>>
String[][] tmp = { { "a.1", "b.2", "c.3" }, { "a.2", "d.1", "e.1" },
{ "b.3", "f.1", "z.1" } };
List<List<String>> test = new ArrayList<List<String>>();
for (String[] array : tmp) {
test.add(new ArrayList<String>(Arrays.asList(array)));
}
// keep track of elements we've already seen
Set<String> nameCache = new HashSet<String>();
// iterate and remove if seen before
for (List<String> list : test) {
for (Iterator<String> it = list.iterator(); it.hasNext();) {
String element = it.next();
String name = element.split("\\.")[0];
if (nameCache.contains(name)) {
it.remove();
} else {
nameCache.add(name);
}
}
}
System.out.println(test);
Output
[[a.1, b.2, c.3], [d.1, e.1], [f.1, z.1]]
List<List<Pair>> inputs; // in whatever format you have them
List<List<Pair>> uniqued = new ArrayList<>(); // output to here
Set<String> seen = new HashSet<String>();
for (List<Pair> list : inputs) {
List<Pair> output = new ArrayList<>();
for (Pair p : list)
if (seen.add(p.getName()))
output.add(p);
uniqued.add(output);
}
Create a Set. Iterate over the list of lists' items. See if the item is in the Set. If it is already there, ignore it. If it isn't, add it to the Set and the list of lists.
Your method will return a new list of lists, not modify the old one. Modifying a list while iterating over it is a pain.

Categories