下面是HashMap中包含的值

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

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

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

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


当前回答

芬兰湾的科特林回答

获取第一个键,然后获取键的值。Kotlin有first()函数:

val list = HashMap<String, String>() // Dummy HashMap.

val keyFirstElement = list.keys.first() // Get key.

val valueOfElement = list.getValue(keyFirstElement) // Get Value.

其他回答

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

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

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

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

Object myValue = statusName.get(myKey);

你可以试试这个:

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

请记住,HashMap并不保证插入顺序。使用LinkedHashMap来保持顺序的完整性。

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

输出:

 Active
 33

更新: 在Java 8或更高版本中获取第一个密钥。

Optional<String> firstKey = map.keySet().stream().findFirst();
if (firstKey.isPresent()) {
    String key = firstKey.get();
}

记住,一般来说,插入顺序在映射中是不受尊重的。试试这个:

    /**
     * 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;
    }

我只在确定map.size() == 1时才使用它。

Java 8的方法,

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

这也是一个很好的方法:)

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