I have this Java Map:
Can you tell me how I can get the 6-th element of the Map?
private static final Map cache = new HashMap<
A HashMap
does not maintain the order of the elements inserted in it. You can used a LinkedHashMap
instead which maintains the order of the elements inserted in it.
Though you need to note that even a LinkedHashMap
has no such method which would give the element at a particular index. You will have to manually iterate through the entries and extract the element at the 6th iteration.
There is no Order in HashMap
. You can obtain the list of may keys using map.keySet()
but there's no guarantee the key set will be in the order which you add it in. Use LinkedHashMap
instead of HashMap
It will always return keys in same order (as insertion)
HashMaps do not preserve ordering:
LinkedHashMap which guarantees a predictable iteration order.
Example
public class Users
{
private String Id;
public String getId()
{
return Id;
}
public void setId(String id)
{
Id = id;
}
}
Users user;
LinkedHashMap<String,Users> linkedHashMap = new LinkedHashMap<String,Users>();
for (int i = 0; i < 3; i++)
{
user = new Users();
user.setId("value"+i);
linkedHashMap.put("key"+i,user);
}
/* Get by position */
int pos = 1;
Users value = (new ArrayList<Users>(linkedHashMap.values())).get(pos);
System.out.println(value.getId());
You need to use a LinkedHashMap
in order to be able to tell the order of the inserted elements. HashMap
is not capable of doing so.
A HashMap
doesn't have a position. You can iterate through its KeySet
or EntrySet
, and pick the nth element, but it's not really the same as a position. A LinkedHashMap does have a position, since it has a predictable iteration order.
Use LinkedHashMap instead of HashMap It will return keys in same order (as insertion) when calling keySet().
For mare detail about LinkedHashMap see this
For example to get the element from specific index
Create a new list from your values and get the value based on index.
LinkedHashMap<String, List<String>> hMap;
List<List<String>> l = new ArrayList<List<String>>(hMap.values());
l.get(6);