remove element from hash map if key is empty - java

how can I find an element of an HashMap in Java, if the HashMap is of the form and one key is empty, so it only contains a blank character.
In my example:
Let wordMap be an instance of HashMap filled with elements.
if (wordMap.containsKey("")) {
wordMap.remove("");
}
This didn´t work. I hope someone can help me.
After I did this, I convert the hash map to a tree map and sort it by the biggest Integer. I print that to the console and this is what I get with
System.out.println("results: " + tree)
I get on the console:
results: { =194, in=73, ...}
Thanks

You can do a couple of different things. For your issue, I would do:
if (wordMap.containsKey(" ")) {
wordMap.remove(" ");
}
However, to be more comprehensive I would iterate over the keys and remove any key that passes the StringUtils.isEmpty() test.

Are you trying to retrieve the value? If yes, then you need replace that
wordMap.remove("");
with
wordMap.get("");
Otherwise, if you're trying to remove the Entry with a key "" that is the correct way to do it.

If you are using Java 8,
then you can apply the following solution.
wordMap.entrySet()
.removeIf(e -> StringUtils.isBlank(e.getKey()));
Here StringUtils.isBlank can be replaced with custom logic to check for invalid keys.

Related

**EMERGE** (Java) Hashmap single key multi values, locate key in multi values Node

The code below just to demonstrate an example of my code.
LinkedHashMap<String, String> studentID = new LinkedHashMap<String, String>();
//studentID.put("P01", "P06" + "P07");
studentID.put("P02", "P08" + "P09");
studentID.put("P03", "P10");
studentID.put("P04", "P11");
studentID.put("P05", "P12");
System.out.println(studentID.containsValue(P06));
So what I am struggling here is when there are multiple values in hashmap, Java will not be able to put up individual value as human do, for instance, System.out.println(studentID.containsValue(P06));, I am trying to locate P06 only but the program will display false as in it cannot pick up multiple values, in fact, it merged multiple values into one. Does anyone knows any solutions the I can search a single value when that value is based in a multi-values hashmap, and also but break when comes to using a key to search and allocate all values in the line, thank you.
You can use the stream API.
boolean found = studentID.values().stream().
anyMatch(value -> value.contains("P06"));
System.out.println(found);

get the value of a list in hashmap in java (not in a sequential manner)

I have an issue regarding getting the value of a hashmap in this form <String, List<time,value>>. If I want to simplify my problem the data structure is in the following format:
{data1=[fetchTime=123, value=1], [fetchTime=124, value=8], [fetchTime=125,value=0],
data2=[fetchTime=123, value=3], [fetchTime=124, value=8], [fetchTime=125, value=6], data3=[fetchTime=123, value=6], [fetchTime=124, value=9], [fetchTime=125, value=1]}
What I want to do is to calculate the sum of the values of the "same" fetch time. so basically I want to sum up the values of the fetch time of 123 which is (1+3+6) and for fetch time of 124 (8+8+9) and so on.
At this point I just care about the algorithm or any hint not the exact running code, so please suggest me how to do that.
Thank you!
As a simple solution, you could use another hashmap:
ie. resultMap<fetchTime, [long]sum> :)
for each item in hashmap
//+ extra for for each item of your list
if (resultMap.contains(item.fetchTime))
resultMap.put(item.fetchTime, item.value + resultMap.get(item.value))
else
resultMap.put(item.fetchTime, item.value)
for each item in resultMap
... print keys and values

Removing values from a Java hashmap

Lets say I do Map<String, Integer> map = new HashMap<String, Integer>();
map.containsValue(value) returns true whether or not the value is found in the hashmap. But I found that there is no way to remove a value. Like map.removeValue(value). You can only remove the key, as in, map.removeKey(key).
Now, my question is, does removing the key also remove the value?
So when I search map.containsValue(value), will it return false if I deleted the key associated with the value with map.removeKey?
Now, my question is, does removing the key also remove the value?
Yes. Sort of.
Actually, it removes the specific entry that consists of the key and the value.
If the value is also used in another entry, then that other entry is unaffected, and the value will still show up in the values collection.
So when I search map.containsValue(value), will it return false if I deleted the key associated with the value with map.removeKey?
It depends ... see above.
This information can easily be found by reading the javadoc carefully.
(The problem with the "try it and see" approach is that it is easy to write a "black box" test that will cause you to drawing the wrong conclusions. I would only suggest "try it and see" if the javadoc did NOT contain the information. And I'd add "read the source" ... )

How can I use a map for calculations?

I'm working on a program for class. Using a TreeMap to store IDs (String - Key) and earnings amounts (double - value). I'm importing the values from a text file using a Scanner. My problem at the moment is that I need the values to accumulate rather than overwriting with the last value read. So my question is how do you use a Map to do calculations like that? Any help would be appreciated.
There is no implicit functionality in Map. Idea behind your homework assignment is for you to learn how to insert, find, get and replace to/from a Map. There are functions for each of these and ou should use all to get this done.
When adding a new value to your map, if the key already exists, you can get the associated value, add the new value to it, and put it back into the map. Example:
// Assuming that key and value were read from your file, and that
// myMap is declared as "Map<String, Double>"
if (myMap.containsKey (key)) {
double oldValue = myMap.get (key);
value += oldValue;
}
myMap.put (key, value);
1) Check whether value with same key exists in the map
2) If it exists then read it and add the currently read value. Put it back into map

problem getting value from HashMap

Hi all I'm using a HashMap to hold one of my object with a string key. when I put an object with a key it has no problem, when I put my second object I got my object added but can't get it with its key. Somewhat it goes to somewhere that is "next". I took a screenshot from debug mode (eclipse), below
although size shows 2, I can't see my second item in hashmap, but in other hashmap's next node.
To note something I use my key like in a form "name.tag", tag and name in same time can never be the same, but "tag" can be the same. does hashmap has something to do with dot operator when evaluating keys? I hope I could write clearly,
Thanks in advance
Edit:
Here is a piece of code I use to create my hashmap
private HashMap<String,ParameterItem> parseParametersNode(DataModel parent,Element element){
NodeList parameterChilds=element.getChildNodes();//gep element parameters
HashMap<String, ParameterItem> parameterItems=new HashMap<String, ParameterItem>();
for(int i=0;i<parameterChilds.getLength();i++){
if(parameterChilds.item(i).getNodeType()==Node.ELEMENT_NODE){
Element el=(Element) parameterChilds.item(i);
NamedNodeMap atts=el.getAttributes();
ParameterItem item=new ParameterItem();
for(int j=0;j<atts.getLength();j++){
Attr attribute=(Attr) atts.item(j);
String attributeValue=attribute.getValue();
String attributeName=attribute.getName();
item.setParsedProperty(attributeName, attributeValue);
} /*check attributes later*/
//finish loop and insert paramitem to params
String key="key"+i;
if(item.getTag()!=null && item.getName()!=null)
key=item.getName()+"."+item.getTag();
parameterItems.put(key, item);
// testParam=item;
// parameterItems.put(key, testParam);
}
}
return parameterItems;
}
There is not really a problem here: you have a hash collision. That is, both of your keys have been placed in the same hash bucket. It appears you have only four buckets (odd, I thought the initial default was 10 or 16), so the chance of that with random data is 25 percent. Your size incremented just fine. The next is the internal implementation’s way of pointing to the next element in the same bucket. If the number of elements in each buckets gets too big, Java will internally rehash into more buckets.
I do not see why you need a HashTable here since you are numbering your keys consecutively (you could use an ArrayList), but maybe this is just starter code and your real use case is different.
You have the code:
String key="key"+i;
but right after this you set key again not adding to it:
if(item.getTag()!=null && item.getName()!=null)
key=item.getName()+"."+item.getTag();
Should this be key +=item.getName()+"."+item.getTag(); ?

Categories