package com.codegym.task.task08.task0806;
import java.util.HashMap;
import java.util.Map;
/*
HashMap of Objects
*/
public class Solution {
public static void main(String[] args) throws Exception {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("Sim", 5);
map.put("Tom", 5.5);
map.put("Arbus", false);
map.put("Baby", null);
map.put("Cat", "Cat");
map.put("Eat", new Long(56));
map.put("Food", new Character('3'));
map.put("Gevey", '6');
map.put("Hugs", 111111111111L);
map.put("Comp", (double) 123);
Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
while (iterator.hasNext())
{
// Get a key-value pair
Map.Entry<String, Object> pair = iterator.next();
String key = pair.getKey(); // Key
String value = pair.getObject(); // Value
System.out.println(key + "-" + value);
//write your code here
/* for(Map.Entry<String,String> p:map.entrySet()){
String key=p.getKey();
String value=p.getValue();
System.out.println(key+"-"+value); */
}}}
How to transverse through objects
Under discussion
Comments (5)
- Popular
- New
- Old
You must be signed in to leave a comment
hacks patel
22 December 2018, 14:36
Object Value = pair.getValue();
use this
0
hacks patel
22 December 2018, 14:35
use object instead of String in value
0
Sindhura
4 October 2018, 10:16
I am getting following error while doing this in same way as pointed by you
com/codegym/task/task08/task0806/Solution.java:31: error: incompatible types: java.lang.Object cannot be converted to java.lang.String
String value = pair.getValue(); // Value
^
0
Ankush Rajput
4 October 2018, 13:49
Read my comment carefully. I said - Object value = pair.getValue();
Replace String with Object.
0
Ankush Rajput
4 October 2018, 03:10
Your program is almost correct, just a few mistakes.
1. You have to import iterator and set from util package. You can do it manually or just do import.java.util.*; to import everything.
2. Check carefully following line of your code -
Its getValue() and not getObject(). There is no such function as getObject in Map.Entry class.
getValue function will return an object and not string.
Put it as Object value = pair.getValue();
3. In println method, put space on both sides of hypen (-) to match the task conditions. " - "
Rest is fine. It'll work. +2