Java HashMap - 获取第一个键值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26230225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:02:55  来源:igfitidea点击:

HashMap - getting First Key value

javahashmap

提问by Prabu

Below are the values contain in the HashMap

以下是 HashMap 中包含的值

statusName {Active=33, Renewals Completed=3, Application=15}

Java code to getting the first Key (i.e Active)

获取第一个 Key(即 Active)的 Java 代码

Object myKey = statusName.keySet().toArray()[0];

How can we collect the first Key "Value" (i.e 33), I want to store both the "Key" and "Value" in separate variable.

我们如何收集第一个键“值”(即 33),我想将“键”和“值”都存储在单独的变量中。

采纳答案by Ruchira Gayan Ranaweera

You can try this:

你可以试试这个:

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

Keep in mind, HashMapdoes not guarantee the insertion order. Use a LinkedHashMapto keep the order intact.

请记住,HashMap不保证插入顺序。使用 aLinkedHashMap保持顺序不变。

Eg:

例如:

 Map<String,String> map = new LinkedHashMap<>();
 map.put("Active","33");
 map.put("Renewals Completed","3");
 map.put("Application","15");
 Map.Entry<String,String> entry = map.entrySet().iterator().next();
 String key= entry.getKey();
 String value=entry.getValue();
 System.out.println(key);
 System.out.println(value);

Output:

输出:

 Active
 33

回答by Suresh Atta

how can we collect the first Key "Value" (i.e 33)

我们如何收集第一个键“值”(即 33)

By using youMap.get(keyYouHave), you can get the value of it.

通过使用youMap.get(keyYouHave),您可以获得它的价值。

want to store the Both "Key" and "Value" in separate variable

想要将“键”和“值”存储在单独的变量中

Yes, you can assign that to a variable.

是的,您可以将其分配给变量。

Wait .........it's not over.

等等…………还没结束。

If you(business logic) are depending on the order of insertions and retrieving, you are going to see weird results. Map is not ordered they won't store in an order. Please be aware of that fact. Use some alternative to preserve your order. Probably a LinkedHashMap

如果您(业务逻辑)依赖于插入和检索的顺序,您将看到奇怪的结果。地图未订购,它们不会按订单存储。请注意这一事实。使用一些替代方法来保留您的订单。大概一个LinkedHashMap

回答by Bohemian

To get the "first" value:

要获得“第一个”值:

map.values().toArray()[0]

To get the value of the "first" key:

要获取“第一个”键的值:

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

Note: Above code tested and works.

注意:以上代码经过测试并有效。

I say "first" because HashMap entries are not ordered.

我说“第一”是因为 HashMap 条目没有排序。

However, a LinkedHashMap iterates its entries in the same order as they were inserted - you could use that for your map implementation if insertion order is important.

但是, LinkedHashMap 以与插入相同的顺序迭代其条目 - 如果插入顺序很重要,您可以将其用于地图实现。

回答by tmarwen

Note that you should note that your logic flow must never rely on accessing the HashMapelements in some order, simply put because HashMaps are not ordered Collections and that is not what they are aimed to do. (You can read more about odered and sorter collections in this post).

请注意,您应该注意您的逻辑流绝不能依赖于HashMap以某种顺序访问元素,简单地说,因为HashMaps 不是有序的Collections 并且这不是它们的目的。(您可以在这篇文章中阅读有关 odered 和 sorter 集合的更多信息)。

Back to the post, you already did half the job by loading the first element key:

回到帖子,你已经通过加载第一个元素键完成了一半的工作:

Object myKey = statusName.keySet().toArray()[0];

Just call map.get(key)to get the respective value:

只需调用map.get(key)即可获取相应的值:

Object myValue = statusName.get(myKey);

回答by Veera

You can also try below:

您也可以尝试以下方法:

Map.Entry<String, Integer> entry = myMap.firstEntry();
System.out.println("First Value = " + entry);

回答by whoami

Java 8 way of doing,

Java 8 的做法,

String firstKey = map.keySet().stream().findFirst().get();

String firstKey = map.keySet().stream().findFirst().get();

回答by Maxime Claude

Remember that the insertion order isn't respected in a map generally speaking. Try this :

请记住,一般来说,地图中不遵守插入顺序。尝试这个 :

    /**
     * Get the first element of a map. A map doesn't guarantee the insertion order
     * @param map
     * @param <E>
     * @param <K>
     * @return
     */
    public static <E,K> K getFirstKeyValue(Map<E,K> map){
        K value = null;
        if(map != null && map.size() > 0){
            Map.Entry<E,K> entry =  map.entrySet().iterator().next();
            if(entry != null)
                value = entry.getValue();
        }
        return  value;
    }

I use this only when I am sure that that map.size() == 1.

仅当我确定map.size() == 1.

回答by George Siggouroglou

You may also try this for getting the entire first entry,

您也可以尝试使用此方法获取整个第一个条目,

Map.Entry<String, String> entry = map.entrySet().stream().findFirst().get();
String key = entry.getKey();
String value = entry.getValue();

This to get only the key of the first entry,

这仅获取第一个条目的键,

String key = map.entrySet().stream().map(Map.Entry::getKey).findFirst().get();
// or better
String key = map.keySet().stream().findFirst().get();

This to get only the value of the first entry,

这仅获取第一个条目的值,

String value = map.entrySet().stream().map(Map.Entry::getValue).findFirst().get();
// or better
String value = map.values().stream().findFirst().get();

Moreover, in case you know what you are doing and you wish to get the second (same for third etc) item of a map, you should try this,

此外,如果您知道自己在做什么并且希望获得地图的第二个(第三个等)项目,您应该尝试这个,

Map.Entry<String, String> entry = map.entrySet().stream().skip(1).findFirst().get();
String key = map.keySet().stream().skip(1).findFirst().get();
String value = map.values().stream().skip(1).findFirst().get();

回答by Jan Bodnar

Improving whoami's answer. Since findFirst()returns an Optional, it is a good practice to check if there is a value.

改进 whoami 的答案。由于findFirst()返回的是Optional,因此检查是否存在值是一个好习惯。

 var optional = pair.keySet().stream().findFirst();

 if (!optional.isPresent()) {
    return;
 }

 var key = optional.get();

Also, some commented that finding first key of a HashSetis unreliable. But sometimes we have HashMappairs; i.e. in each map we have one key and one value. In such cases finding the first key of such a pair quickly is convenient.

此外,有些人评论说找到 a 的第一个键HashSet是不可靠的。但有时我们有HashMap成对的;即在每张地图中我们有一个键和一个值。在这种情况下,快速找到这样一对的第一个密钥是很方便的。

回答by Adrian

Also a nice way of doing this :)

也是这样做的好方法:)

Map<Integer,JsonObject> requestOutput = getRequestOutput(client,post);
int statusCode = requestOutput.keySet().stream().findFirst().orElseThrow(() -> new RuntimeException("Empty"));