Specifically, I want to use a LinkedHashMap in a "for each" loop. For example, let's say I create a LinkedHashMap:
LinkedHashMap<String, Integer> someHash = new LinkedHashMap<String, Integer>();
Then I fill it with some things:
someHash.put("One", new Integer(1));
someHash.put("Two", new Integer(2));
Now how might I be able to go through and get each pair? I want something along the lines of:
for(<String, Integer> pair : someHash)
{
//Do stuff.
}
But of course this doesn't work. Is there a simple way to retrieve a "pair" object from the hash? Or do I just have to iterate through the length and get the value and key separately? Also, should I really be using a different object if this is the case?
You can use Map.Entry to simulate the Pair object that exists in C++.
for(Map.Entry<String, Integer> entry : someHash.entrySet())
{
System.out.println("Key: " + entry.getKey() + " Value: " + entry.getValue());
}
Here the entrySet is the all key/value pairs from your Map.
Use like this
LinkedHashMap<String, Integer> someHash = new LinkedHashMap<String, Integer>();
someHash.put("One", new Integer(1));
someHash.put("Two", new Integer(2));
for(String key : someHash.keySet())
{
System.out.println("Key : "+key + " Value : "+someHash.get(key));
}
Related
I have a method which returns out hashmap of hashmaps
HashMap<String, HashMap<String, String>> mapofmaps = abcd(<String>, <Integer>);
I am trying to print the the outer hashmap using the following code
for (Entry<String, HashMap<String, String>> entry : mapofmaps.entrySet()) {
String key = entry.getKey();
System.out.println(key);
HashMap<String, String> value = entry.getValue();
System.out.println(key + "\t" + value);
}
I would like to iterate through the inner map. What would be the entryset variable there (??? in the code).
for (Entry<String, HashMap<String, String>> entry : mapofmaps.entrySet()) {
String key = entry.getKey();
System.out.println(key);
for(Entry<String, HashMap<String, String>> entry : ????.entrySet()){
HashMap<String, String> value = entry.getValue();
System.out.println(key + "\t" + value);
}}
Is my logic for printing the hashmaps correct? or is there a better way to do that?
It will be entry.getValue().entrySet()
so
for(Entry<String, String> innerEntry : entry.getValue().entrySet()){
then you can use
String key = innerEntry.getKey();
String value = innerEntry.getValue();
It is worth mentioning that, this can also be done Using java 8 Streams and lambda expressions
HashMap<String, HashMap<String, String>> mapofmaps = new HashMap<>();
HashMap<String,String> map1 = new HashMap<>();
map1.put("map1_key1", "map1_value1");
HashMap<String,String> map2 = new HashMap<>();
map2.put("map2_key1", "map2_value1");
mapofmaps.put("map1", map1);
mapofmaps.put("map2", map2);
// To print the keys and values
mapofmaps.forEach((K,V)->{ // mapofmaps entries
V.forEach((X,Y)->{ // inner Hashmap enteries
System.out.println(X+" "+Y); // print key and value of inner Hashmap
});
});
mapofmaps.forEach((K,V) : This expects a lambda expressions which takes two inputs i.e Key (String) and Value (HashMap)
V.forEach((X,Y)->{ : As this is applied on inner (V: fetched through previous foreach) hashmap so both Key and Value will be strings
Reference for further reading :
Lambda Expressions
Map foreach description
A Straight forward example with data
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 10);
map.put("Motorolla", 20);
map.put("RealMe", 30);
map.put("Oppo", 40);
map.put("Sony", 50);
map.put("OnePlus", 60);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ", Stock : " + entry.getValue());
}
Using lambda expression
map.forEach((K,V) -> System.out.println(K + ", Stock : " + V));
I've got a TreeMap that stores a HashMap inside of it. I feel like I should be able to find this, but I just can't seem to find it on Google.
I've got a TreeMap with a HashMap stored inside of it, I iterate over it like so:
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
That will print out an output (example line):
I/System.outīš 32: {walks=32, pic=http://****/images/walkers/chase.png, name=Chase, dist=6096.8589024135445}
I'm wondering how to now grab pic, name, dist from this HashMap.
Edit: I'm not understanding where people missed the point. I put a HashMap into the TreeMap. Inside of the TreeMap is a HashMap. I guess I can show you what a HashMap is, but you guys know that already!
TreeMap dist_mp=new TreeMap();
Map<String, String> mp1 = new HashMap<String,String>();
mp1.put("dist", distanceInMiles + "");
mp1.put("name", obj.getString("first_name"));
mp1.put("pic", obj.getString("pic"));
mp1.put("walks", obj.getString("walks"));
dist_mp.put(distanceInMiles, mp1);
All you need is a cast to the TreeMap values to a Map again:
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
System.out.print(me.getKey() + ": ");
// Cast to a Map again
Map<String, String> mp = (Map<String, String>) me.getValue();
// get() works now
System.out.print("name = " + mp.get("name"));
System.out.print("pic = " + mp.get("pic"));
System.out.println("dist = " + mp.get("dist"));
}
Need to iterate twice, one for TreeMap and then for HashMap
public static void main(String[] args) {
TreeMap<String, Map<String, String>> dist_mp = new TreeMap<String, Map<String, String>>();
Map<String, String> mp1 = new HashMap<String, String>();
mp1.put("dist", "6096.8589024135445");
mp1.put("name", "Chase");
mp1.put("pic", "http://****/images/walkers/chase.png");
mp1.put("walks", "32");
dist_mp.put("32", mp1);
for (Map.Entry<String, Map<String, String>> entry : dist_mp.entrySet()) {
String key = entry.getKey();
System.out.println(key);
Map<String, String> myMap = entry.getValue();
for (Map.Entry<String, String> entry1 : myMap.entrySet()) {
System.out.println(entry1.getKey() + " => " + entry1.getValue());
}
}
}
output
32
walks => 32
name => Chase
pic => http://****/images/walkers/chase.png
dist => 6096.8589024135445
Your HashMap seems to be holding an object of some class, which is depicted here:
{walks=32, pic=http://****/images/walkers/chase.png, name=Chase, dist=6096.8589024135445}
Identify the class, and if getter methods are available for pic, name, dist, then use them.
I think you are just asking how to get the value associated with a key:
map.get("pic");
You want me.getValue().get("pic"), me.getValue().get("name") and me.getValue().get("dist").
This assumes that you're using generics, that your TreeMap is declared as a Map<Integer, HashMap<String, String>> and that your Map.Entry that you iterate with is declared as a Map.Entry<Integer, HashMap<String, String>>.
Also, you could iterate more easily with a for-each loop.
Map<Integer, HashMap<String, String>> theTreeMap = new TreeMap<>();
// Populate the map here.
for (Map.Entry<Integer, HashMap<String, String>> me : theTreeMap.entrySet()) {
System.out.println(me.getValue().get("pic"));
System.out.println(me.getValue().get("name"));
System.out.println(me.getValue().get("dist"));
}
I am using a map inside another map, The key of the outer map is Integer and the value is another Map. I get the values as expected but I don't know how to get the key and value of teh inner map.
Here is the code
Map<Integer, Map<Integer, Integer>> cellsMap = new HashMap<Integer, Map<Integer, Integer>>();
Map<Integer , Integer> bandForCell = cellsMap.get(band_number);
if (bandForCell == null)
bandForCell = new HashMap<Integer, Integer>();
bandForCell.put(erfcn, cell_found);
cellsMap.put(band_number, bandForCell);
csv.writeCells((Map<Integer, Map<Integer, Integer>>) cellsMap);
public void writeCells (Map<Integer, Map<Integer, Integer>> cellsMap ) throws IOException
{
for (Map.Entry<Integer, Map<Integer, Integer>> entry : cellsMap.entrySet()) {
System.out.println("Key: " + entry.getKey() + ". Value: " + entry.getValue() + "\n");
}
}
Out put of my Map
Key: 20 Value: {6331=0, 6330=1, 6329=1, 6328=0, 6335=1, 6437=0, 6436=1}
The value in the above output is another map.
How can I get the key and value of the inner map from the value of the outer map?
Like Keys of inner map = 6331, 6330, 6329 ....
and values of inner map = 0 , 1 , 1 , 0 ...
Thanks
This worked for me , Hope it will help someone else in future
for (Map.Entry<Integer, Map<Integer, Integer>> outer : cellsMap.entrySet()) {
System.out.println("Key: " + outer.getKey() + "\n");
for (Map.Entry<Integer, Integer> inner : entry.getValue().entrySet()) {
System.out.println("Key = " + inner.getKey() + ", Value = " + inner.getValue());
}
}
In order to get a reference to an inner map, you would just use cellsMap.get(key). I'm not sure exactly what you want to do, but, for example, if you wanted to get the value where the first key was i and the second key was j, you could get it using cellsMap.get(i).get(j)
Or, if you wanted to print out all the keys and values of the inner map at index i, you could use
for (Map.Entry> entry : cellsMap.get(i).entrySet()) {
System.out.println("Key: " + entry.getKey() + ". Value: " + entry.getValue() + "\n");
}
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 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.