Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there a elegant way of obtaining only one Entry<K,V> from HashMap, without iterating, if key is not known.

As order of entry of entry is not important, can we say something like

hashMapObject.get(zeroth_index);

Although I am aware that there exist no such get by index method.

If I tried approach mentioned below, it would still have to get all the entry set of the hashmap.

for(Map.Entry<String, String> entry : MapObj.entrySet()) {
    return entry;
}

Suggestions are welcome.

EDIT: Please suggest any other Data Structure to suffice requirement.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
208 views
Welcome To Ask or Share your Answers For Others

1 Answer

Maps are not ordered, so there is no such thing as 'the first entry', and that's also why there is no get-by-index method on Map (or HashMap).

You could do this:

Map<String, String> map = ...;  // wherever you get this from

// Get the first entry that the iterator returns
Map.Entry<String, String> entry = map.entrySet().iterator().next();

(Note: Checking for an empty map omitted).

Your code doesn't get all the entries in the map, it returns immediately (and breaks out of the loop) with the first entry that's found.

To print the key and value of this first element:

System.out.println("Key: "+entry.getKey()+", Value: "+entry.getValue());

Note: Calling iterator() does not mean that you are iterating over the whole map.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...