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);
Related
Here is the Java code to find the shortest concatenation of elements of Array wordBank to construct String Terget, using Dynamic Programming.
Example:
Input: wordBank = {"ab", "c", "d", "abc", "ad"},
Target = "abcd".
Output: {"abc", "d"}.
To do this, I have stored the combination of elements as an ArrayList in a HashMap.
However, the hashMap does not store the values correctly, i.e., the values change when I recursively call the function, although I have cloned the ArrayList before adding it to the map.
Any idea why this happens?
The code works well with arrays.
static ArrayList<String> bestConstruct(String target, String[] wordBank, HashMap<String, ArrayList<String>> map) {
if(target.isEmpty())
{
return new ArrayList<String>();
}
if(map.containsKey(target))
return map.get(target);
ArrayList<String> shortestCombination = null;
for (String word : wordBank) {
if(target.startsWith(word)) {
String newTarget = target.substring(word.length(), target.length());
ArrayList<String> combination = bestConstruct(newTarget, wordBank, map);
if(combination != null) {
combination.add(word);
if(shortestCombination == null || combination.size() < shortestCombination.size())
shortestCombination = (ArrayList<String>)(combination.clone());
}
}
}
map.put(target, (ArrayList<String>) (shortestCombination.clone()));
return shortestCombination;
}
The problem is the interaction between these lines:
if(map.containsKey(target))
return map.get(target);
and
ArrayList<String> combination = bestConstruct(newTarget, wordBank, map);
if(combination != null) {
combination.add(word);
If you return the memoized list, you're updating it before you clone it.
In general, don't rely on callers to "do the right thing": if you don't want the list in the map to be updated, do the copy yourself before you return it:
if(map.containsKey(target))
return new ArrayList<>(map.get(target));
You may also need to handle the case of a string not being able to be constructed from the word bank.
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);
}
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);
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);
I am trying to make a HashMap that takes the value as a List<Pack> where Pack is an object that I created, then adds Packs to this list if the condition is true.
Now I get errors even though the condition is true, and I think I did not initialize it correctly can someone tell me where the problem is?
static HashMap<Long, List<Pack>> ackPkts = new HashMap<Long, List<Pack>>();
static HashMap<Long, List<Pack>> dataPkts = new HashMap<Long, List<Pack>>();
static List<Pack> pktList = new ArrayList<Pack>();
if((msg.getPayloadLength()) == 0 && (msg.isSYN()) == false && (msg.isACK()) == true){
Pack pack = new Pack(msg.getAck(), msg.sackPresent(), captureTime, srcIP, destIP, msg.isSYN());
(ackPkts.get(msg.getAck())).add(pack);
} else {
Pack pack = new Pack(msg.getSeq(), captureTime, srcIP, destIP,
msg.getPayloadLength(), msg.isSYN());
(dataPkts.get(msg.getSeq())).add(pack);
}
The List<Pack> in your HashMaps are never defined. They are of the interface list but nowhere you identify what kind of List they are. You have to follow a structure as follows:
Map<long, List<Pack>> map = new HashMap<>() // java 7 syntax
List<Pack> packets = new ArrayList<>();
packets.add(pack);
map.put(msg.getAck(), packets);
When adding an element to the ´List´, which you now can because it exists, you do:
map.get(msg.getAck()).add(pack);
You want to put List instances in first Maps before you use add() on them:
static List<Pack> datapktList = new ArrayList<Pack>();
static List<Pack> actpktList = new ArrayList<Pack>();
Then add respective List instance to Map:
ackPkts.put(msg.getAck(), datapktList );
dataPkts.put(msg.getAck(), actpktList );
Then following would work:
(ackPkts.get(msg.getAck())).add(pack);
(dataPkts.get(msg.getSeq())).add(pack);