Map<Object,String> mp=new HashMap<Object, String>();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the instrument name");
String name=sc.next();
mp.put(name, "Control Valve");
mp.put(name, "BDV");
mp.put(name, "SDV");
mp.put(name, "ON-OFF VALVE");
mp.put(name,"Analyser");
Set s=mp.entrySet();
Iterator it=s.iterator();
while(it.hasNext())
{
Map.Entry m =(Map.Entry)it.next();
String key=(String)m.getKey();
String value=(String)m.getValue();
System.out.println("Instrument name :"+key+" fields:"+value);
}
}
}
In this only last value is mapped to the key .i.e analyser to key .
How to map all the values to one key entered by the user .And also it has to ask user to enter values for each value field.
updated code -:It asks for instrument name but then shows exception “java.util.ArrayList cannot be cast to java.lang.String”
Map<String,List<String>> mp=new HashMap<String,List<String>>();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the instrument name");
String name=sc.next();
List<String> valList = new ArrayList<String>();
valList.add("Control Valve");
valList.add("BDV");
valList.add("SDV");
valList.add("ON-OFF VALVE");
valList.add("Analyser");
mp.put(name, valList);
Set s=mp.entrySet();
Iterator it=s.iterator();
while(it.hasNext())
{
Map.Entry m =(Map.Entry)it.next();
String key=(String)m.getKey();
String value=(String)m.getValue();
System.out.println("Instrument name :"+key+" fields:"+value);
}
}
}
I would suggest to use
So that you can maintain set of values to a given key.
if a list available for given key , get the list and add the new value to list.
UPDATED