I hava a structure Map :
Map<String, Double> map = new LinkedHashMap<>();
I don't know the key, but I want to pick up the first element and the last element, how can I achieve conveniently.
I hava a structure Map :
Map<String, Double> map = new LinkedHashMap<>();
I don't know the key, but I want to pick up the first element and the last element, how can I achieve conveniently.
Getting the first is easy - request an iterator
and take it's next
.
// Needs null checks etc.
String first = map.keySet().iterator().next();
Getting the last is covered in Java get last element of a collection.
one way to do this:
Map<String, Double> map = new LinkedHashMap<>();
map.put("one", 2.0);
map.put("two", 12.0);
map.put("three", 44.0);
String lKeyFirst = null;
String lKeyLast = null;
if (!map.isEmpty()){
lKeyFirst = map.keySet().iterator().next();
for(String key : map.keySet()){
lKeyLast = key;
}
System.out.println("First key: " +lKeyFirst);
System.out.println("Last key: " +lKeyLast);
}
Output:
First key: one
Last key: three
of course isEmpty
is never false in this case.
EDIT:
@Test
public void testMapOneValue() {
Map<String, Double> map = new LinkedHashMap<>();
map.put("one", 2.0);
String lKeyFirst = null;
String lKeyLast = null;
if (!map.isEmpty()){
lKeyFirst = map.keySet().iterator().next();
for(String key : map.keySet()){
lKeyLast = key;
}
System.out.println("First key: " +lKeyFirst);
System.out.println("Last key: " +lKeyLast);
}
}
Output:
First key: one
Last key: one