Reputation:
I need help trying to iterate through a Hashmap with objects. i got really stuck on how to do this. I tried checking on links like this How to iterate through objects in Hashmap but couldn't still implement it exactly as i want.
List<Object> firstObject = new ArrayList<Object>();
HashMap<Integer, Object> mapEx = new HashMap<> ();
/* Put the data to Map*/
mapEx.put(1, "First"); // String
mapEx.put(2, 12.01); // float
mapEx.put(3, 12345); // int
mapEx.put(4, 600851475143L); // Long
/* add map to firstObject */
firstObject.add(mapEx);
HashMap<String, Object> secondMap = new HashMap<> ();
secondMap.put("mapEx", firstObject);
Log.d("mapEx: ",secondMap.get("mapEx").toString());
//When i print the line, this is the result below
D/mapEx:﹕ [{4=600851475143, 1=First, 3=12345, 2=12.01}]
But How can i actually iterate through them? to come out this way.
4=600851475143
1=First
3=12345
2=12.01
and also maybe call each one by its key.
Thanks in advance.
Upvotes: 1
Views: 4723
Reputation: 22254
The example you linked does answer the question. This how it would look like for your case :
for (Map.Entry<Integer, Object> entry : mapEx.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
Also java 8 solution with streams
mapEx.entrySet().stream().forEach(e ->
System.out.println(e.getKey() + "=" + e.getValue())
);
Tutorials about HashMaps here and here
And for streams here
Upvotes: 2
Reputation: 1819
Like this:
for (HashMap<Object, Object> map : firstObject) {
for (Object key : map.keySet()) {
Object value = map.get(key);
System.out.println("key = " + key + " value = " + value);
}
}
Upvotes: 0