I have a HashMap, which contains another HashMap. I want to iterate over the first HashMap and use the Key values from that. Then, as I iterate over the first HashMap I want to start an inner loop iterating over the second HashMap, getting all the values.
The problem I have so far is that I can't figure out how to get the keys from the Iterator.
HashMap<String, HashMap<Integer, String>> subitems = myHashMap.get("mainitem1");
Collection c = subitems.values();
Iterator itr = c.iterator();
while(itr.hasNext())
{
// Get key somehow? itr.getKey() ???
// contains the sub items
HashMap productitem = (HashMap)itr.next();
}
The data that i get from subitems is this:
{Item1{0=sub1, 1=sub2}, Item2{0=sub3, 1=sub4}}
Then, in the while loop productitem contains the 'sub items'. But i can't find out where i can get the key value 'Item1' and 'Item2' from.
How can i get those?
You can't get the key from values().iterator().
You need to use entrySet().iterator(). That will return Map.Entry<K,V> objects on which you can call getKey() and getValue().
for (Map.Entry<Integer,Key> entry : subitems.keySet()) {
Integer key = entry.getKey();
String value = entry.getValue();
// do stuff
}
I'd also like to add that having deeply nested maps of lists of maps is usually a sign that you really want to write custom classes to hold your data. Especially when the maps have pre-defined keys to be used and interpretation of the values in the lists depends on the position within the list! I call this code smell "object denial".
You can't go from value to key in a map. (There may be several keys mapping to the same value!)
You can iterate over the map entries though using subitems.entrySet().iterator(), or you can iterate over the keys, and in each iteration retrieve the associated value through subitems.get(key).
You could do something like this (using iterators):
Set<Entry<String, HashMap<Integer, String>>> c = subitems.entrySet();
Iterator<Entry<String, HashMap<Integer, String>>> iterator = c.iterator();
while(iterator.hasNext())
{
Entry<String, HashMap<Integer, String>> entry = iterator.next();
System.out.println("key:" + entry.getKey());
HashMap<Integer, String> innerMap = entry.getValue();
if (innerMap == null) {
continue;
}
Iterator<Entry<Integer, String>> innerIterator = innerMap.entrySet().iterator();
while (innerIterator.hasNext()) {
Entry<Integer, String> innerEntry = innerIterator.next();
System.out.println("key:" + innerEntry.getKey() + " value: " + innerEntry.getValue());
}
}
or like this using foreach structure:
for (Entry<String, HashMap<Integer,String>> entry : subitems.entrySet())
{
System.out.println("key:" + entry.getKey());
HashMap<Integer, String> innerMap = entry.getValue();
if (innerMap == null) {
continue;
}
for (Entry<Integer, String> innerEntry : innerMap.entrySet())
System.out.println("key:" + innerEntry.getKey() + " value: " + innerEntry.getValue());
}
}
java Collections provide facility of EntrySet. This is a list of objects which contain individual keys and values as its properties. You can take a iterator out of this list.
You can get keys as follows.
Iterator i= subitems.entrySet().iterator();
while(i.hasNext()){
String key= i.next().getkey();
}
You can iterate over entries using entrySet().iterator() on the first HashMap or get the keys and iterate over them: Instead of subitems.values().iterator() use subitems.keys().iterator() and use the next key to get the inner hashmap.
Related
I want to print the keys of my HashMap "allDishes".
This HashMap contains an Dish as the value.
The Dish class has a HashMap field named "Ingredients".
I want to print the key of the "allDishes" and the keys of its HashMap "Ingredients".
With the foreach keySet(),
the key for Ingredients is "null",
because there is no value in "Ingredient" like there is in "allDishes".
Is it possible at all to print keys of different HashMaps?
Map<String, Dish> allDishes = (Map<String, Dish>) application.getAttribute("allDishesHashMap");
for (String key : allDishes.keySet()) {
Map <String, String> Ingredient = allDishes.get(key).getIngredients();
out.println("<li><b>" + key + "</b> with: </li>" + Ingredient.get(key));
}
You are doing it wrong.
Currently,
you are iterating through the keys of the allDishes HashMap.
What you want to do is iterate through the keys of the allDishes HashMap and
for each key in the allDishes HashMap,
iterate through the keys of Ingredient HashMap contained within the current dish in the allDishes HashMap.
To do this,
first iterate through the allDishes entrySet,
then iterate through the ingredients keySet for each entry.
Here is some code:
final Map<String, Dish> dishMap = (Map<String, Dish>)application.getAttribute("allDishesHashMap");
for (final Map.Entry dishEntry: dishMap.entrySet())
{
final Map <String, String> ingredientMap = dishEntry.getIngredients();
out.println("<li><strong>" + dishEntry.getKey() + "</strong> Ingredients: <ul>");
for (final String ingredientName : ingredientMap.keySet())
{
out.println("<li>" + ingredientName + "</li>")
}
out.println("</ul></li>");
}
You can print them with nested loops and a null check.
Map<String, Dish> allDishes = (Map<String, Dish>)
application.getAttribute("allDishesHashMap");
for (String dishKey : allDishes.keySet()) {
Map <String, String> ingredients = allDishes.get(dishKey).getIngredients();
System.out.println("Dish Key: " + dishKey);
// check if null here, if necessary
if (ingredients == null) {
continue; // continue, or print something else. whatever you need
}
for (String ingredient : ingredients.keySet()) {
System.out.println("Ingredient Key: " + ingredient);
}
}
You can also print a "keyset" directly like the following if you don't need any special formatting on the keysets.
Map<String, Dish> allDishes = (Map<String, Dish>)
application.getAttribute("allDishesHashMap");
for (String key : allDishes.keySet()) {
Map <String, String> ingredients = allDishes.get(key).getIngredients();
System.out.println("Dish Key: " + key);
// check if null here, if necessary
if (ingredients == null) {
continue; // continue, or print something else. whatever you need
}
System.out.println("Ingredients KeySet: " + ingredients.keySet());
}
I want iterate a TreeMap until a specific key .
for (int i = 0 ; i < specifickey ; i++)
How can i do this ?
TreeMap implements NavigableMap which can be useful to iterate over a range of keys.It is internally backed by the Map,so any changes you do to the Map is reflected vice-versa.You should use a headMap(K toKey, boolean inclusive) to get the map
NavigableMap<K,V> navigableMap = map.headMap(toKey, true);
for(Map.Entry entry : navigableMap .entrySet()){
//use the key value pair in Map.Entry
}
If you just want to iterate over the keys:
for (String key : map.keySet()) {
if (key.equals(target)) {
// do something
}
}
If you also need to access the values, then it's more efficient to iterate over the entries instead of the keys:
Map<String, Integer> map = new TreeMap<>();
String target = "something";
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getKey().equals(target)) {
// do something with entry.getValue()
}
}
Like every other map:
Map<Integer, Object> map = ...;
for (int key : map.keySet()) {
if(key == yourValue) {
//value found
}
}
Edit: Read your question again, if you only want to find out, if a key is present, then:
if(map.containsKey(key)) {
//do something
}
I'm new to hash table and I'm just figuring out the basic operations on it.
I have a hash table created as shown below and inserted values also.
Hashtable<Integer , String> ht = new Hashtable<Integer , String>();
ht.put(1234, "ABCD");
ht.put(2345, "EFGH");
ht.put(4567, "IJKL");
I am able to delete the element needed using the key as shown below
System.out.println("Deleting entry with key 2345");
ht.remove(2345);
System.out.println(ht.toString());
which gives the following output
Deleting entry with key 2345
{4567=IJKL, 1234=ABCD}
I am not able to find any method which helps with locating the element in the hashtable using the value as an index and deleting the element. How do I go about it?
try this
ht.values().remove("ABCD");
this will remove one entry with the specified value, if there may be multiple entries with the same value you can use this
ht.values().removeAll(Collections.singleton("ABCD"));
Navigate using Map.entrySet() and check for Map.Entry#getValue() equality.
You can have a value multiple times so iterate entrySet using an Iterator and delete elements using Iterator.remove()
void deleteItem(String item) {
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> entry = it.next();
if(entry.getValue().equals(item)) {
it.remove();
}
}
}
Map<Integer, String> map = ...
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> entry = it.next();
// Remove entry if value equals xxx.
if (entry.getValue() != null && entry.getValue().equals("X")) {
// Do something
}
}
Good day, this is kind of confusing me now(brain freeze!) and seem to be missing something. Have an ArrayList which i populate with a HashMap. now i put in my HashMap and arraylist.
Map.put(DATE, value1);
Map.put(VALUE, value2);
arraylist.put(Map);
Since am parsing a JSON, the arraylist increases in significant size. now my question is how do you get the values from both map keys in the arraylist? i have tried this
if(!list.isEmpty()){ // list is an ArrayList
for(int k = 0; k < list.size(); k++){
map = (HashMap)list.get(k);
}
}
Log.d(TAG, "map size is" + map.size());
String [] keys = new String[map.size()];
String [] date_value = new String[map.size()];
String [] value_values = new String[map.size()];
int i = 0;
Set entries = map.entrySet();
Iterator iterator = entries.iterator();
while(iterator.hasNext()){
Map.Entry mapping = (Map.Entry)iterator.next();
keys[i] = mapping.getKey().toString();
date_value[i] = map.get(keys[i]);
if(keys[i].equals(DATE)){
date_value[i] = map.get(keys[i]);
} else if(keys[i].equals(VALUE)){
value_values[i] = map.get(keys[i]);
}
i++;
}
But i can't seem to get all the values. the Map size always return a value of 2, which is just the elements. how can i get all the values from the Map keys in the ArrayList? Thanks
Why do you want to re-invent the wheel, when you already have something to do your work. Map.keySet() method gives you a Set of all the keys in the Map.
Map<String, Integer> map = new HashMap<String, Integer>();
for (String key: map.keySet()) {
System.out.println("key : " + key);
System.out.println("value : " + map.get(key));
}
Also, your 1st for-loop looks odd to me: -
for(int k = 0; k < list.size(); k++){
map = (HashMap)list.get(k);
}
You are iterating over your list, and assigning each element to the same reference - map, which will overwrite all the previous values.. All you will be having is the last map in your list.
EDIT: -
You can also use entrySet if you want both key and value for your map. That would be better bet for you: -
Map<String, Integer> map = new HashMap<String, Integer>();
for(Entry<String, Integer> entry: map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
P.S.: -
Your code looks jumbled to me. I would suggest, keep that code aside, and think about your design one more time. For now, as the code stands, it is very difficult to understand what its trying to do.
List constructor accepts any data structure that implements Collection interface to be used to build a list.
To get all the keys from a hash map to a list:
Map<String, Integer> map = new HashMap<String, Integer>();
List<String> keys = new ArrayList<>(map.keySet());
To get all the values from a hash map to a list:
Map<String, Integer> map = new HashMap<String, Integer>();
List<Integer> values = new ArrayList<>(map.values());
Try it this way...
I am considering the HashMap with key and value of type String, HashMap<String,String>
HashMap<String,String> hmap = new HashMap<String,String>();
hmap.put("key1","Val1");
hmap.put("key2","Val2");
ArrayList<String> arList = new ArrayList<String>();
for(Map.Entry<String,String> map : hmap.entrySet()){
arList.add(map.getValue());
}
Create an ArrayList of String type to hold the values of the map. In its constructor call the method values() of the Map class.
Map <String, Object> map;
List<Object> list = new ArrayList<Object>(map.values());
Put i++ somewhere at the end of your loop.
In the above code, the 0 position of the array is overwritten because i is not incremented in each loop.
FYI: the below is doing a redundant search:
if(keys[i].equals(DATE)){
date_value[i] = map.get(keys[i]);
} else if(keys[i].equals(VALUE)){
value_values[i] = map.get(keys[i]);
}
replace with
if(keys[i].equals(DATE)){
date_value[i] = mapping.getValue();
} else if(keys[i].equals(VALUE)){
value_values[i] = mapping.getValue()
}
Another issue is that you are using i for date_value and value_values. This is not valid unless you intend to have null values in your array.
This is incredibly old, but I stumbled across it trying to find an answer to a different question.
my question is how do you get the values from both map keys in the arraylist?
for (String key : map.keyset()) {
list.add(key + "|" + map.get(key));
}
the Map size always return a value of 2, which is just the elements
I think you may be confused by the functionality of HashMap. HashMap only allows 1 to 1 relationships in the map.
For example if you have:
String TAG_FOO = "FOO";
String TAG_BAR = "BAR";
and attempt to do something like this:
ArrayList<String> bars = ArrayList<>("bar","Bar","bAr","baR");
HashMap<String,String> map = new HashMap<>();
for (String bar : bars) {
map.put(TAG_BAR, bar);
}
This code will end up setting the key entry "BAR" to be associated with the final item in the list bars.
In your example you seem to be confused that there are only two items, yet you only have two keys recorded which leads me to believe that you've simply overwritten the each key's field multiple times.
Suppose I have Hashmap with key datatype as KeyDataType
and value datatype as ValueDataType
HashMap<KeyDataType,ValueDataType> list;
Add all items you needed to it.
Now you can retrive all hashmap keys to a list by.
KeyDataType[] mKeys;
mKeys=list.keySet().toArray(new KeyDataType[list.size()]);
So, now you got your all keys in an array mkeys[]
you can now retrieve any value by calling
list.get(mkeys[position]);
Java 8 solution for produce string like "key1: value1,key2: value2"
private static String hashMapToString(HashMap<String, String> hashMap) {
return hashMap.keySet().stream()
.map((key) -> key + ": " + hashMap.get(key))
.collect(Collectors.joining(","));
}
and produce a list simple collect as list
private static List<String> hashMapToList(HashMap<String, String> hashMap) {
return hashMap.keySet().stream()
.map((key) -> key + ": " + hashMap.get(key))
.collect(Collectors.toList());
}
It has method to find all values from map:
Map<K, V> map=getMapObjectFromXyz();
Collection<V> vs= map.values();
Iterate over vs to do some operation
I have the following Java code:
public void myMethod (final Map pFeatureGroupsFromPackage) {
final Set<String> keys = pFeatureGroupsFromPackage.keySet();
for (final String key : keys) {
tmpList = (List<FeatureKey>) pFeatureGroupsFromPackage.get(key);
// do whatever
}
}
I am getting a warning from "findBugs" telling the following:
Method myMethod makes inefficient use of keySet iterator instead of entrySet iterator.
The warning is done at the tmpListassignment.
I do not understand why this is inefficient. In fact the keyslist is computed only once.
Any comment? Thanks.
Instead of iterating over the keySet and calling get to get the corresponding value for each key, iterate over the entrySet:
final Set<Map.Entry<String, List<FeatureKey>>> entries = pFeatureGroupsFromPackage.entrySet();
for (Map.Entry<String, List<FeatureKey>> entry : entries) {
String key = entry.getKey();
List<FeatureKey> tmpList = entry.getValue();
// do whatever
}
That way you don't have to do a lookup in the map for every key; you directly get the key and value in one go.
Also, declare your Map with type parameters:
public void myMethod (final Map<String, List<FeatureKey>> pFeatureGroupsFromPackage) {
// ...
}
you're getting all the keys and then you search for every key in the collection
a Map.EntrySet iteration would be much faster, a small example:
But you also should use generics...
Set entries = map.entrySet();
Iterator entryIter = entries.iterator();
System.out.println("The map contains the following associations:");
while (entryIter.hasNext()) {
Map.Entry entry = (Map.Entry)entryIter.next();
Object key = entry.getKey(); // Get the key from the entry.
Object value = entry.getValue(); // Get the value.
System.out.println( " (" + key + "," + value + ")" );
}
This could help you:
Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
Integer key = (Integer)entry.getKey();
Integer value = (Integer)entry.getValue();
System.out.println("Key = " + key + ", Value = " + value);
}
Sample code:
for (Map.Entry < Integer, List < FeatureKey >>> i: map.entrySet()) {
System.out.println(i.getValue() + " " + i.getKey()));
}
It could be that you are querying the map twice:
first for the keys,
and second for the values
Using entryset iterator will iterate over the map once.
Accessing the HashMap via keySet iterator is even faster than using the keySet iterator on the TreeMap.
Hey Luixv,
The reason using keysey iterator is less effective than entryset iteratot is that with the first option you still have to use the Map.get(key) lookeup which is avoided with the second option.