Returning entryset in map using key value - java

I have two string value ID and Value coming from my code, I need to store this in a map without iterating over the map but by checking by the key value if it exists in the map.
The ID can come many times with different value and in that case I have add it to the already existing entry of the ID and add the value along with the existing value
I created a Map with String and List to add the values but I am facing difficulties,
Map < String, List< String >> accessMap = new HashMap < String, List< String>>();
If the key is not present, add a new entry with ID and Value (as List).
How to find the key in the map and get the entrySet without iterating over the map and add the value alone, if the ID is already present in the map.
Example,
while(accessList.hasNext()){
....
....
String id = accessEntry.get(ID);
String value = accessEntry.get(Value);
/*Add the id and value to the map if not present, if ID is present add the *value alone to the entrySet.Value (which is a list)
*/
}
The id and value has to be added into a map checking if the ID is already present in the map, if not create a new entry.
The accessList might have many ID references with different value, in that case the value should be added to the entrySet of the already existing entry, the value would be a list with single value or multiple value.

public static void add(Map<String, Set<String>> map, String key, String value) {
map.compute(key, (id, values) -> {
(values = Optional.ofNullable(values).orElseGet(LinkedHashSet::new)).add(value);
return values;
});
}
For values it is better to use Set to exclude duplications.

Use computeIfAbsent() to initialise a List for the id if one doesn't exist already, then just add the value to that:
entitlementMap.computeIfAbsent(id, s -> new ArrayList<>()).add(value);

Related

How to remove an element from a set that is in a map

I'm trying to remove an element from a set that is in a map but I'm unsure how to do it.
The code I have so far is:
public void deleteToValue(String aLocation, String aEquipment)
{
locationMap.remove(aLocation, aEquipment);
}
The map key is the location and the the set is called equipment.
Assume the location is London and I want to remove a bike from the set.
The key and set will always be present so there's no need to check for nulls at this point.
This requires 2 steps:
Set<String> equipment = locationMap.get(aLocation) => returns the set
equipment.remove(aEquipment) ==> removes equipment from set.
If I understood you correctly, you have a map -> Map<String, Set<String>> and you want to remove equipment for some location.
Please, consider this code:
public void deleteToValue(String aLocation, String aEquipment)
{
Set<String> equip = locationMap.get(aLocation);
if (equip != null) {
equip.remove(aEquipment);
}
}
When calling map .get(..key..) method, it returns a value associated with a provided key, in your case, your value is Set<>.
So, to remove something from the set, firtly you need to read it from the map by key -> Set<String> equip = locationMap.get(aLocation); and then remove the required item from the Set -> equip.remove(aEquipment);

Deleting a value only from a key on HashMap

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

How Can I search a Integer in a TreeMap<String, List<Integer>>? [duplicate]

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.

Value of HashMap inside a Hashmap in Java

I have this hashmap of students which stores the id, name and last name.
So I created this :
Map<Interger, HashMap<String,String>> students = new HashMap<>();
where the second hashmap stores the name and lastname.
My goal is to look for a student in a swing application, I succeed in searching with id because it's the key of the first hashmap, but i'd like to use all of them like this:
So my question is : If I want to search by name or last name, how can i get the value of the first hashmap and put it in a new hashmap ?
You can iterate on the hashmap like this :
private int searchByName(String s) {
for(Map.Entry<Integer, HashMap<String, String>> entry : students.entrySet()) {
HashMap student = entry.getValue(); // Hashmap containing first and lastname
if (student.containsKey(s)) // If name match
return entry.getKey(); // Return the student ID
}
return 0; // Student not found
}
For the lastname just use containsValue(s) instead of containsKey(s)
You can use the Google Collections API Guava for that specifically a BiMap
A bimap (or "bidirectional map") is a map that preserves the
uniqueness of its values as well as that of its keys. This constraint
enables bimaps to support an "inverse view", which is another bimap
containing the same entries as this bimap but with reversed keys and
values.
With this you'will be able to search using first name and last name. This BiMap will be value to your first parent hashmap.
I am not sure if the data structure is the best for your use-case but answering to your question, you should try using values() method which would return you the collection of values of the Map
http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#values()
Collection res = studensts.values();
Iterator<HashMap<String, String>> i = res.iterator();
Map<String,String> resM = null;
while(i.hasNext()){
resM = i.next();
}

How to retrieve a collection of values from a HashMap

I'm writing a function to test if a HashMap has null values. The method .values() SHOULD return a collection of just the values, but instead I receive a map with both the keys and values stored inside. This is no good as the purpose of my function is to check if the values are null, but if I return a map with keys AND values then .values().isEmpty() returns false if I have a key stored with no value.
public Map<KEY, List<VALUES>> methodName() {
if (MAPNAME.values().isEmpty()) {
throw new CustomErrorException(ExceptionHandler.getErrorWithDescription(ErrorConstants.ERROR_MSG_01));
} else {
return MAPNAME;
}
}
In the above example, .values() always returns a map containing all the keys and values. My method never throws a CustomErrorException if the HashMap has a key, which is bad since it's supposed to detect if there are no values. Help!
There's no such thing as a Map implementation that has a key stored without a value. All Map implementations either:
throw an exception in put when the value is null
Add an entry with a key and a value of null
A key that maps to null is very different than a key without a value. The key has a value, and that value is null (and that means that the values collection won't be empty, unless the map is empty). A key without a value is a key that's not contained in the map.
Long story short, you probably want to use MAPNAME.values().contains(null) or even just MAPNAME.containsValue(null) to do what you want. Alternatively, if you're checking that every key maps to null, check that by iterating over the .values() collection.
You're returning the map -- MAPNAME, not the values:
return MAPNAME.values();
If you're trying to determine if the map contains any null values, you should iterate over the collection of values and check each one to see if its null.
A map that contains an entry with a null value is not empty.
You're not being very clear about what you want -- your map values are lists -- considering that, there are three ways to have a key map to "no values":
A key mapped to null (then the test is map.values().contains(null) )
A key mapped to an empty list (then the test is map.values().contains(Collections.emptyList()) )
A key mapped to a list full of nulls.
What your method above is doing right now is throwing an exception if the map is truly empty (no keys), and returning the map otherwise.
It is not clear what you want. If you want the method to throw an exception only if the map has no meaningful values (all keys map either to null or to empty lists) then something like this is what you need:
public Map<KEY, List<VALUES>> methodName() {
for( List<VALUES> values : MAPNAME.values() ) // 1
if( null != values ) // 2
for( VALUES value : values ) // 3
if( null != value ) // 4
return MAPNAME;
throw new CustomErrorException(ExceptionHandler.getErrorWithDescription(ErrorConstants.ERROR_MSG_01));
}
This throws an exception in the all reasonably conceivable "empty map" scenarios -- if (1) the map is truly empty, or (2) it contains only null keys, or (3) it only contains only null values or empty lists, or (4) it contains only null values or empty lists or lists of nulls.
(Levels of "emptiness" tests in the text above correspond to the comment labels in the code).
Use the values() method in this way:-
Collection set=MAPNAME.values();
And then use a foreach loop to check if every value is null or not.

Categories