I have a hashmap that is 101 keys in size, but I know for sure about 6 of those have no data inside, and there may be more without data as well. What exactly is inside the empty indexes? Is it null? or is there a Hash(index).isEmpty() method that I can use to see if its empty?
I realize there is a isEmpty method inside hashmap, but I thought that only checked if the entire map was empty not just a single index.
I realize there is a isEmpty method
inside hashmap, but I thought that
only checked if the entire map was
empty not just a single index.
I think what you're looking for is the containsKey(Object) method. According to the documentation:
Returns true if this map contains a
mapping for the specified key. More
formally, returns true if and only if
this map contains a mapping for a key
k such that (key==null ? k==null :
key.equals(k)). (There can be at most
one such mapping.)
Parameters:
key - key whose presence in this map is to be tested
Returns:
true if this map contains a mapping for the specified key
Well, for the keys to arrive there with no data, you have to put them there.
If you did map.put(key, null) then yes the data for that key is null. You always have to give the second parameter to the method, you can't just map.put(key).
If you know for sure that a certain key should have no data you could try going into debug mode and putting a watch for myMap.get(myEmptyKey) and see what you get (in case that no data is an empty object or something else, you should be able to see that).
Edit: Some code would be useful to help you, but if I understand correctly you do something like this:
for (Object obj : list) {
if (matchesCriteriaX(obj)) {
map.put("X", obj);
else if (matchesCriteriaY(obj)) {
map.put("Y", obj);
}
}
Well, if you do that and try to do map.get("X"), but you never actually put anything for that key (becaus no object matched criteria X), you will most definitely get back a null.
On the other hand, if you did something like
Map<String, List<Object>> map = new HashMap<String, List<Object>>();
map.add("X", new ArrayList<Object>());
map.add("Y", new ArrayList<Object>());
for (Object obj : list) {
if (matchesCriteriaX(obj)) {
List<Object> list = map.get("X");
list.add(obj);
else if (matchesCriteriaY(obj)) {
List<Object> list = map.get("Y");
list.add(obj);
}
}
then you could check if a category is empty by doing map.get("x").isEmpty() since List has that method (and it would be empty if no object matched the key criteria).
Judging from what you said, I'm suspecting something like this:
Map<SomeKey, List<SomeValue>> yourMap;
If this is the case, what you can do is
if( yourMap.contains(someKey) ){
List<SomeValue> someList = yourMap.get(someKey);
if(someList.size() == 0){
// it's empty, do something?
}
}
Related
I am working on an XML file. In my XML file, there are somes nodes which have childs. This XML file has multiple tags.
<Cat categorie="CAT 1" guid="e9fdsd8ff">
<!--Electric energie management-->
**<item Var="VAR1" guid="2795ddsd410d">
<desc> Energie Smart Management
</desc>
<App guid="240adsqsd" />
<App guid="90dqddqsq" />**
</item>
</Cat>
Like you can see, my node "item " has the argument VAR=var1 and has 2 childs.
So I created a hashMap to put, for 1 node his childs like below
private Map<String, Collection <String >> multiMap = new HashMap <> ();
So I Have something like that actually : [Key=Var1, Value = [gui0,guid1,...]]
Now, I would like to know if you knew how to verify if a guid is contained in a collection associated with a key in order to retrieve this key.
For example, if I have this String : 240adsqsd. I want to recover Var1.
Thanks for your help
It is possible.
Say you have the key myKey and you want to know if the string mySearchString is contained in the collection behind that key.
multiMap.get("myKey").contains("mySearchString");
It will return true if mySearchString equals (case sensitive) any object in the colelction.
You have to be careful though, the method contains on a collection uses the case sensitive equals method and will only work when they are 100% equal. So when your collection contains something like "MYSEARCHstring", it won't work, as well as "The sentence that contains mySearchString".
EDIT:
(Thanks Nikolas and Dici)
Here a more complete example how to achieve that.
String mySearchString = "mySearchString";
Map<String, Collection<String>> multiMap = new HashMap<>();
for (String key : multiMap.keySet()) {
if (multiMap.get(key) != null && multiMap.get(key).contains(mySearchString)) {
return key;
}
}
If you don't know the key, you have to iterate over your map, check if one of the collections contains the searched string and then, when you found the collection (and its key) return the key.
A test without map modification would be:
boolean contained = multiMap.getOrDefault(key, Collections.emptyList()).contains(key);
Then there are Map.computeIfAbsent, computeIfPresent, merge if you want to update the map.
If I understand your question, you actually want to reverse your map because a map is good at accessing a value given a key not at finding a key given a value. Here's some pseudo-code to build the map:
map = new Map()
for item in items
for app in item.apps
map.put(app.guid, item.guid) // assuming guids are always unique
That would give you a Map<String, String> rather than Map<String, Collection<String>>. The former is good at telling you which item contains an application, the later is good at telling you which apps a given item contains. Given your reverse mapping map, you will be able to do the following:
// could just have Map<App, Item> appToItem if you build your map differently
// and App and Item define hashCode and equals
public boolean findVar(String appId, Map<String, String> appToItem, Map<String, Item> itemsById) {
Item item = itemsById.get(appToItem.get(appId));
if (item == null) return null;
return item.getVar();
}
Thank you to everyone for your answers.
If I understand correctly, it is preferable that I look for a value not his key.
So let's admit that I choose this option.
Can I recure each value for a key.
If my key is Var1 for example, would it be better for me to recover all its values?
I have set up a HashMap which populates with customers details as values (name, postcode, item) and the keys being say Customer1, Customer2 etc.
I want a method to delete just value "item" from each key, my code at the moment is as per below but when i run it the "item" value from argument isn't deleted.
public void deleteThisValue(String value)
{
if (this.customer.containsValue(value))
{
this.customer.remove(value);
}
}
Now in my head this works but it obviously doesn't, can anyone shed any light on this matter?
Thanks
You can simply iterate over the values...then invoking the get method of the map will return the reference of the value, on that reference you can invoke a setter.
myMap.get(x).setItem("newItem");
//or
myMap.get(x).setItem(-1);
it depends what is Item for a type....
example:
Map<String, Pojo> myMap = new HashMap<>();
myMap.put("A", new Customer2());
myMap.put("B", new Customer2());
myMap.put("C", new Customer2());
for (String x : myMap.keySet()) {
myMap.get(x).setItem("newItem");
//or
myMap.get(x).setItem(-1);
}
System.out.println(myMap);
Edit:
since java8 is offering streams, you can use those nice features doing:
myMap.values().stream().forEach(x -> x.setItem("none"));
remove method works with key only,
If you want to remove value only, then you can set value as null for that key.
e.g:
this.customer.put(key,null);
But if you want to set a particular value (say item) of value then you can do this something like that:
this.customer.get(key).setItem(null);
I'm checking to see if a key in my HashMap exists, if it does, I also want to check to see if any other keys have a value with the same name as that of the original key I checked for or not.
For example I have this.
System.out.println("What course do you want to search?");
String searchcourse = input.nextLine();
boolean coursefound = false;
if(hashmap.containsKey(searchcourse) == true){
coursefound = true;
}
This checks to see if the key exists in my hashmap, but now I need to check every single key's values for a specific value, in this case the string searchcourse.
Usually I would use a basic for loop to iterate through something like this, but it doesn't work with HashMaps. My values are also stored in a String ArrayList, if that helps.
You will want to look at each entry in the HashMap. This loop should check the contents of the ArrayList for your searchcourse and print out the key that contained the value.
for (Map.Entry<String,ArrayList> entries : hashmap.entrySet()) {
if (entries.getValue().contains(searchcourse)) {
System.out.println(entries.getKey() + " contains " + searchcourse);
}
}
Here are the relevant javadocs:
Map.Entry
HashMap entrySet method
ArrayList contains method
You can have a bi-directional map. E.g. you can have a Map<Value, Set<Key>> or MultiMap for the values to keys or you can use a bi-directional map which is planned to be added to Guava.
As I understand your question, the values in your Map are List<String>. That is, your Map is declares as Map<String, List<String>>. If so:
for (List<String> listOfStrings : myMap.values()) [
if (listOfStrings .contains(searchcourse) {
// do something
}
}
If the values are just Strings, i.e. the Map is a Map<String, String>, then #Matt has the simple answer.
I'm trying to add an object to a Hashset within a Hashmap.
Here gamesAndTeams is a Hashmap, and it contains a Hashset.
I've looked over some tutorials over the web but what I'm trying isn't working.
Am I doing something wrong?
Match newmatch = new Match(dateOfGame, stad, guestTeam, hostTeam, hostGoals, guestGoals);
gamesAndTeams.put(key, gamesAndTeams.get(key).add(newmatch));
You must first check if the key is present in the HashMap. If not, you should create the value HashSet and put it in the HashMap :
if (gamesAndTeams.containsKey(key))
gamesAndTeams.get(key).add(newmatch);
else {
HashSet<Match> set = new HashSet<>();
gamesAndTeams.put(key,set);
set.add(newmatch);
}
or
HashSet<Match> set = gamesAndTeams.get(key);
if (set == null) {
set = new HashSet<>();
gamesAndTeams.put(key,set);
}
set.add(newmatch);
Yes.
Assuming gamesAndTeams already has an entry for key, you just want
gamesAndTeams.get(key).add(newmatch);
...you don't need to put anything in the map unless it was previously not in the map at all.
I have this code:
for(GlCapabs_e capName : capabs.keySet()){
x = capName.get();
}
where GlCapabs_e is an enum and capabs is an EnumMap<GlCapabs_e, Boolean>. But GlCapabs_e type up there is wrong, as I can't use get() on capName; it can't be a constant, it has to be a type to support get() so to return the value of the key.
I've read somewhere in Java documentation (I can't find it anymore) that a "special" type exists like elementOf, itemOf or something alike but googling them didn't return anything pertaining my matter. And above this I'm not sure whether it's this type that I'm supposed to use.
You're iterating over the keySet. If you want to get the value mapped to each key in the key set, use the EnumMap to retrieve the value
for(GlCapabs_e capName : capabs.keySet()){
x = capabs.get(capName);
}
Or iterate over the entrySet
for (Entry<GlCapabs_e, Boolean> entry : capabs.entrySet()) {
x = entry.getValue(); // the entry holds both the key and the mapped value
}
Remember, EnumMap is an implementation of Map, it therefore inherits/implements all of its methods.