java loop and add values to a map
17,717
Solution 1
Use Iterator insted of EntrySet
Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();
Iterator itr=map.keySet().iterator();
while (itr.hasNext()) {
String key = itr.next().toString();
String value=map.get(key).toString();
System.out.println(key+"="+value);
}
Solution 2
This is what you need:
anotherMap.forEach((k, v) -> myMap.put(k.toString(), v.toString()));
Source: Looping Through a Map in Java
Author by
user3736748
Updated on June 07, 2022Comments
-
user3736748 almost 2 years
New to using map and was wondering how to add values and loop thur it to retrieve the values. Below is my code:
Map<String, List<String>> map = new LinkedHashMap<String, List<String>>(); for ( int i = 0, m = 1; i < visualcategory.size(); i = i+2, m = m+2) { String categoryName = visualcategory.get(m); map.put(categoryName , null); }
for which i will be having this which is im assuming is correct even with the null
MAP {5=null, 11=null, 15=null, 24=null, 96=null, 98=null}
Its currently null as the next process (below) will fill up that list as it loops thru a for condition unless it can be done to add the categoryName and the List values at the same time?
Now, i need to loop and add a list from each string/map
String value1 = value; String value2 = value; for (Entry<String, List<String>> entry : map.entrySet()) { map.put(value1, entry.getValue()); --> doesn't work map.put(value2, entry.getValue()); --> doesn't work }
I need something like this
MAP {5=[value1,value2,etc], 11=[value1,value2,etc], .......
Problem is, it doesn't work I can't seem to add inside the List. I need help on how to add values from a map > and loop thru to it?