HashMap has only one key and Value
Map<String, String> hm = new HashMap<>();
hm.put("one","ele");
Now how to get key and value from this and assign to string?
HashMap has only one key and Value
Map<String, String> hm = new HashMap<>();
hm.put("one","ele");
Now how to get key and value from this and assign to string?
Just iterate through them
for (Entry<String, String> entry : hm.entrySet())
{
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + ":" + value);
}
And you dont need to use HashMap also, as you have only 1 key value pair.
Just create a simple classe to hold your data:
public class Pair {
private String key;
private String value;
public Pair( String k, String v ) {
key = k
value = v;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
}
And the you just need this to use it:
Pair pair = new Pair( "one", "ele );
if (map.entrySet().size() == 1) {
Entry<String, String> next = map.entrySet().iterator().next();
}
Need to use Iterator
on HashMap
public static void printMap(Map hm) {
String key = "";
String value = "";
for (Entry<String, String> entry : hm.entrySet())
{
key = entry.getKey();
value = entry.getValue();
System.out.println(key + ":" + value);
}
}
You need to iterate over map value. Since map can not provide you the indexed access to the values.
Map<String, String> hm = new HashMap<String, String>();
hm.put("one","ele");
Set<Entry<String, String>> entrySet = hm.entrySet();
for (Entry<String, String> entry : entrySet)
{
System.out.println(entry.getKey()+ " " + entry.getValue());
}
or if you have key then you can use
String value = hm.get(key);
it will return you value object.
Map.Entry<String, String> entry = hm.entrySet().iterator().next();
String result = entry.getKey() + " = " + entry.getValue()