下面是HashMap中包含的值

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

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

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

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


当前回答

你可以试试这个:

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

其他回答

你也可以试试下面的方法:

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

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

    /**
     * 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时才使用它。

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

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

Java 8的方法,

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

芬兰湾的科特林回答

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

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

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

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