Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the first key of a hashmap?

Tags:

java

hashmap

I have the following HashMap<String, Double> map = new HashMap<String, Double>();

How can i get the first key without iterating over it like this:

Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pair = (Map.Entry)it.next();
    System.out.println(pair.getKey() + " = " + pair.getValue());
    it.remove(); 
}

Thanks

like image 631
Jürgen K. Avatar asked Feb 26 '16 17:02

Jürgen K.


4 Answers

To get the value of the "first" key, you can use it

map.get(map.keySet().toArray()[0]);

In Java8,

You can use stream. For TreeMap/LinkedHashMap, where ordering is significant, you can write

map.entrySet().stream().findFirst();

For HashMap, there is no order, so findAny() might return a different result on different calls

map.entrySet().stream().findAny();
like image 155
SkyWalker Avatar answered Oct 11 '22 14:10

SkyWalker


if you use Java 8,

map.entrySet().stream().findFirst().get().getKey()
like image 32
karthik r Avatar answered Oct 11 '22 13:10

karthik r


Since your question is not very specific about what you consider the "first key" I will just list a few options.

Just the first one in the key set

String firstKey = map.keySet().iterator().next();

But no idea what information that provides you.

The smallest key

String firstKey = map.keySet().stream().min(String::compareTo).get();

The key of the smallest value

String firstKey = map.entrySet().stream().min((a,b) -> a.getValue().compareTo(b.getValue())).get().getKey();

The first inserted key

This does not work with a regular HashMap because it does not preserve the ordering. Use a LinkedHashMap instead.

Map<String, Double> map = new LinkedHashMap<>();
String firstKey = map.keySet().iterator().next();
like image 20
MartinS Avatar answered Oct 11 '22 14:10

MartinS


Map<String, Double> map=new HashMap<>();
Map.Entry<String, Double> entry=map.entrySet().iterator().next();
 String key= entry.getKey();

But HashMap doesn't maintain insertion order. You can use LinkedHashMap instead of HashMap.

like image 29
Rahman Avatar answered Oct 11 '22 14:10

Rahman