I have a Hashmap and i am struggling on how to print a single key and value. i am able to print all of them but would like to know how to just print one of them thanks
import java.util.HashMap;
public class Coordinate {
static class Coords {
int x;
int y;
public boolean equals(Object o) {
Coords c = (Coords) o;
return c.x == x && c.y == y;
}
public Coords(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int hashCode() {
return new Integer(x + "0" + y);
}
public String toString()
{
return x + ";" + y;
}
}
public static void main(String args[]) {
HashMap<Coords, String> map = new HashMap<Coords, String>();
map.put(new Coords(65, 72), "Dan");
map.put(new Coords(68, 78), "Amn");
map.put(new Coords(675, 89), "Ann");
System.out.println(map.size());
System.out.println(map.toString());
}
}
At the moment it shows
3
{65;72=Dan, 68;78=Amn, 675;89=Ann}
but would like it to just show
65;72=Dan
thanks for looking
The
Map.get(K)method allows you to retrieve the value of a desired key. So you can do this:This works for any sort of Map, including HashMap and TreeMap. You can also obtain a set of all keys in the map using
Map.keySet().