如何在不迭代的情况下从哈希图中获取一个条目 [英] how to get the one entry from hashmap without iterating

查看:19
本文介绍了如何在不迭代的情况下从哈希图中获取一个条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种优雅的方法可以从 HashMap 中只获取一个 Entry,而无需迭代,如果 key 未知.

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);

虽然我知道不存在这样的 get by 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;
}

欢迎提出建议.

请建议任何其他数据结构以满足要求.

Please suggest any other Data Structure to suffice requirement.

推荐答案

Jesper 的回答很好.另一种解决方案是使用 TreeMap(您要求其他数据结构).

The answer by Jesper is good. An other solution is to use TreeMap (you asked for other data structures).

TreeMap<String, String> myMap = new TreeMap<String, String>();
String first = myMap.firstEntry().getValue();
String firstOther = myMap.get(myMap.firstKey());

TreeMap 有开销,因此 HashMap 速度更快,但仅作为替代解决方案的示例.

TreeMap has an overhead so HashMap is faster, but just as an example of an alternative solution.

这篇关于如何在不迭代的情况下从哈希图中获取一个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆