This question already has answers here:
Why do I get a ConcurrentModificationException?
(3 answers)
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
(31 answers)
Closed 4 years ago.
I currently have a problem with removing a key in a hashmap. I created a hashmap within a hashmap. I need to remove a key by the value inside the hashmap within the hashmap. So the hashmap looks like this:
HashMap<String, String> people_attributes = new HashMap<String, String>();
Map<String, HashMap<String, String>> people = new HashMap<String, HashMap<String, String>>();
If I try to remove a key, replace remove_name.add(p_name) with people.remove(p_name) I get java.util.ConcurrentModificationException.
Right now, I use an arraylist to add the keys that needs to be remove, then loop through the arraylist to remove the keys from the hashmap.
So far this is the solution:
for(String p_name : people.keySet()) { // search through people with attribute
for(String p_attributes : people.get(p_name).keySet()) { // search through attributes map
if(p_attributes.equals(g_att)) { // when current attributes equal to guess attribute
p_value = people.get(p_name).get(p_attributes);
if(!p_value.equals(g_value)) { // if current value doesn't equal to guess value
remove_name.add(p_name);
}
}
}
}
for(String r_name : remove_name) {
people.remove(r_name);
}
EDIT:
Problem: I know I can use iterator, like all the other questions ask in stackoverflow, but I don't know how to loop twice to get into people_attributes hashmap.
Related
This question already has answers here:
Iterating over Key Set vs Iterating over Entry Set
(2 answers)
FindBugs warning: Inefficient use of keySet iterator instead of entrySet iterator
(5 answers)
Closed 28 days ago.
I'm scanning my code through SonarQube and it shows this code smell "Iterate over the "entrySet" instead of "keySet"". I tried, but I can't figure it out.
Sample code:
public Set<Date> getAccountShiftDate(Map<String, Set<String>> shiftDatesMap, List<Groups> shiftSchedule) {
// set that has the account shift dates
Set<Date> accountShiftDatesTemplate = new Hashset<>();
// iterate on accounts
for (String accounts : shiftDatesMap.keySet()) {
//get group of an account
Optional <Groups> shiftOptional = shiftList
.stream()
.filter(g -> StringUtils.equalsIgnoreCase(accounts,g.getLongName()))
.findFirst();
// ...
Can someone give me a reference to understand this.
If you iterate over shiftDatesMap.keySet() and later on call in your loop shiftDatesMap.get(accounts) you execute an unnecessary get operation for each entry.
Try to read an understand the description of the metioned code smell from SonarQube.
Instead you should use shiftDatesMap.entrySet() which gives you an Entry, i.e. as pair of the key and the value. So if you later on in your loop want to access the value for your given accounts key, you must only access the value from your entry, which is cheaper than calling a get operation on the map for each value.
Before:
for (String accounts : shiftDatesMap.keySet()) {
Set<String> shiftDates = shiftDatesMap.get(accounts); // unnecessary operation
}
After:
for (Map.Entry<String, Set<String>> entry: shiftDatesMap.entrySet()) {
String accounts = entry.getKey();
Set<String> shiftDates = entry.getValue(); // access value for free without 'get' on map
}
This question already has answers here:
HashMap: One Key, multiple Values
(15 answers)
Closed 2 years ago.
My problem is that I have an Hashtable and I end up with some key having two values. I would like to get both of these value, so I can see which one I want and take it.
Here is an exemple :
Hashtable<String, String> myTable = new Hashtable<>();
myTable.put("key1", "value1");
myTable.put("key1", "value2");
System.out.println(myTable.get("key1"));
//output : value2
How to retrieve both of the value ?
Thank you for your help !
EDIT :
In my tests, the HashTable can't store 2 values like this but I assure that in my project where I have a (I believe) code that does the same thing. When, after my algorithm has ran I System.out.prinln(myTable) it does show multiple time the same key with differents value.
It depends on the way to create a HashTable, in your example. You create a HashTable maps a String to a String, then because the value is a String, you cannot expect the table can store multiple values on one key. When you do the second put method, it will find the key with value key1 and replace the previous value which is mapped to this key to the new one.
If you want to store multiple values on one key, think about the list which will hold multiple values for your key. Here is an example to map a key with a type of String to multiple String values:
Hashtable<String, ArrayList<String>> myTable = new Hashtable<>();
ArrayList<String> listValue = new ArrayList<>();
listValue.add("value1");
listValue.add("value2");
myTable.put("key1", listValue);
System.out.println(myTable.get("key1")); // get all values of the key [value1, value2]
System.out.println(myTable.get("key1").get(0)); // get the first value of this key, value1
System.out.println(myTable.get("key1").get(1)); // get the second value of this key, value2
It is recommended to use HashMap over a HashTable.
In HashMap class, put function adds object if it isn't exist, if it's exist just updates the value. You can create another class to keep values;
class exampleValue {
String v1, v2;
exampleValue() {}
}
and
HashMap<String, exampleValue> h = new HashMap<>();
exampleValue v = new exampleValue();
v.v1 = "a";
v.v2 = "b";
h.put("key", v);
h.get("key").v1; //returns "a"
h.get("key").v2; //returns "b"
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am working on a personal project on Java. I have a Map called allow and the second parameter is another Map. I am trying to compare the second parameter of the Map inside allow. If anyone can help me that would be a big help.
public boolean checkBank(String bank, int cNumber){
Map <String, Map<String, String> > allow = new HashMap<>();
String num = Integer.toString(cNumber);
Iterator<Map.Entry<String, Map<String, String>>> entries = allow.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, Map<String, String>> entry = entries.next();
if (entry.getKey().equals(bank)) {
String all = entry .getValue().get(0);
for (int i = 0; i < entry.getValue().size(); i++) {
if(entry.getValue().equals(num)) {
return true;
}
}
}
}
return false;
}
On the statement: if(entry.getValue().equals(num))
entry.getValue() is a Map, but num is a string. These two are not compatible types, so they can never be equal.
It's worth noting that you are looking for the one entry with the key value equal to bank. Rather than scan through all Map.Entry objects for the one which has the right value, why not just use the statement:
Map<String,String> map = allow.get(bank);
Let the outer map do this work for you.
Your question didn't exactly make clear what you wanted, but I'm guessing that you either want to look, in the inner Map, for an Entry where either the key or the value matches num. You can do that with either
map.containsKey(num)
or
map.containsValue(num)
Is that basically what you are looking for?
This question already has answers here:
How to preserve insertion order in HashMap? [duplicate]
(2 answers)
Closed 6 years ago.
I am trying to get the count of duplicate values of String ArrayList, i have achieved the task but not completely. i am able to get the counts of duplicate elements of my arrayList, but the problem is that the order of arrayList destroys when i get the occurrences of elements
here is my code:
Map<String, Integer> counts = new HashMap<String, Integer>();
for (String str : t.courseName) {
if (counts.containsKey(str)) {
counts.put(str, counts.get(str) + 1);
} else {
counts.put(str, 1);
}
}
for (Map.Entry<String, Integer> entry : counts.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
this code works fine for getting occurrences but note that this code destroys the order. what i want is that the order should also not be destroyed.
Use LinkedHashMap instead of HashMap to preserve the insertion order
A LinkedHashMap is a combination of hash table and linked list. It has a predictable iteration order (a la linked list), yet the retrieval speed is that of a HashMap. The order of the iteration is determined by the insertion order, so you will get the key/values back in the order that they were added to this Map.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I iterate over each Entry in a Map?
I make the personal profiles database,and I use HashMap to collect profile.
private HashMap<String, Profile> database;
but I want to write profile data to text files
PrintWriter fileOut = new PrintWriter(new FileWriter(fileName));
fileOut.println(database.size());
for(int i = 0; i < database.size();i++){
Profile eachProfile = database.get(key);
}
But I don't know how to get list of key to looping
How can I get data from HashMap respectively with another ways?
You could use Map.entrySet() and extended for:
for (Map.Entry<String, Profile> e: database.entrySet())
{
String s = e.getKey();
Profile p = e.getValue();
}
Have a look at the Map documentation here: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html
You want a list of all keys which is available as keySet(). The values() and entrySet() methods are related.
You can use map.keySet to get the set of keys.
You can use map.values to get the collection of values