[英]Java HashMap: How to get a key and value by index?
我正在嘗試使用 HashMap 到 map 一個唯一的字符串到一個字符串 ArrayList 像這樣:
HashMap<String, ArrayList<String>>
基本上,我希望能夠通過數字訪問密鑰,而不是使用密鑰的名稱。 我希望能夠訪問所述鍵的值,對其進行迭代。 我在想象這樣的事情:
for(all keys in my hashmap) {
for(int i=0; i < myhashmap.currentKey.getValue.size(); i++) {
// do things with the hashmaps elements
}
}
是否有捷徑可尋?
如果您真的只想要第一個鍵的值,這是通用解決方案
Object firstKey = myHashMap.keySet().toArray()[0];
Object valueForFirstKey = myHashMap.get(firstKey);
您可以通過調用map.keySet()
迭代鍵,或者通過調用map.entrySet()
迭代條目。 迭代條目可能會更快。
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
List<String> list = entry.getValue();
// Do things with the list
}
如果要確保以插入鍵的相同順序迭代鍵,請使用LinkedHashMap
。
順便說一下,我建議將地圖的聲明類型更改為<String, List<String>>
。 總是最好根據接口而不是實現來聲明類型。
HashMap 不是有序的,除非您使用LinkedHashMap
或SortedMap
。 在這種情況下,您可能需要一個LinkedHashMap
。 這將按照插入的順序(或者如果您願意,可以按照上次訪問的順序)進行迭代。 在這種情況下,它將是
int index = 0;
for ( Map.Entry<String,ArrayList<String>> e : myHashMap.iterator().entrySet() ) {
String key = e.getKey();
ArrayList<String> val = e.getValue();
index++;
}
映射中沒有直接的 get(index) ,因為它是鍵/值對的無序列表。 LinkedHashMap
是保持順序的特殊情況。
已選擇解決方案。 但是,我為那些想要使用替代方法的人發布了這個解決方案:
// use LinkedHashMap if you want to read values from the hashmap in the same order as you put them into it
private ArrayList<String> getMapValueAt(LinkedHashMap<String, ArrayList<String>> hashMap, int index)
{
Map.Entry<String, ArrayList<String>> entry = (Map.Entry<String, ArrayList<String>>) hashMap.entrySet().toArray()[index];
return entry.getValue();
}
你可以這樣做:
for(String key: hashMap.keySet()){
for(String value: hashMap.get(key)) {
// use the value here
}
}
這將迭代每個鍵,然后迭代與每個鍵關聯的列表的每個值。
for (Object key : data.keySet()) {
String lKey = (String) key;
List<String> list = data.get(key);
}
我遇到了同樣的問題,從不同的相關問題中閱讀了幾個答案,並提出了我自己的課程。
public class IndexableMap<K, V> extends HashMap<K, V> {
private LinkedList<K> keyList = new LinkedList<>();
@Override
public V put(K key, V value) {
if (!keyList.contains(key))
keyList.add(key);
return super.put(key, value);
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
for (Entry<? extends K, ? extends V> entry : m.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
keyList.clear();
super.clear();
}
public List<K> getKeys() {
return keyList;
}
public int getKeyIndex(K key) {
return keyList.indexOf(key);
}
public K getKeyAt(int index) {
if (keyList.size() > index)
return keyList.get(index);
return null;
}
public V getValueAt(int index) {
K key = getKeyAt(index);
if (key != null)
return get(key);
return null;
}
}
示例(為了清楚起見,類型與 OP 問題不同):
Map<String, Double> myMap = new IndexableMap<>();
List<String> keys = myMap.getKeys();
int keyIndex = myMap.getKeyIndex("keyString");
String key = myMap.getKeyAt(2);
Double value myMap.getValueAt(2);
請記住,它不會覆蓋任何復雜的方法,因此如果您想可靠地訪問其中之一,則需要自己執行此操作。
編輯:我對 putAll() 方法進行了更改,因為舊方法很少有機會導致 HashMap 和 LinkedList 處於不同狀態。
Kotlin HashMap 答案
您可以通過索引獲取密鑰。 然后通過key獲取值。
val item = HashMap<String, String>() // Dummy HashMap.
val keyByIndex = item.keys.elementAt(0) // Get key by index. I selected "0".
val valueOfElement = item.getValue(keyByIndex) // Get value.
如果您不關心實際的鍵,則迭代所有Map 值的簡潔方法是使用它的values()
方法
Map<String, List<String>> myMap;
for ( List<String> stringList : myMap.values() ) {
for ( String myString : stringList ) {
// process the string here
}
}
values()
方法是 Map 接口的一部分,它返回地圖中值的 Collection 視圖。
HashMap 不會以特定順序保存您的鍵/值對。 它們根據每個鍵從其 Object.hashCode() 方法返回的散列進行排序。 但是,您可以使用迭代器迭代一組鍵/值對:
for (String key : hashmap.keySet())
{
for (list : hashmap.get(key))
{
//list.toString()
}
}
您可以使用 Kotlin 擴展功能
fun LinkedHashMap<String, String>.getKeyByPosition(position: Int) =
this.keys.toTypedArray()[position]
fun LinkedHashMap<String, String>.getValueByPosition(position: Int) =
this.values.toTypedArray()[position]
例如,您需要像這樣創建多個 HashMap
Map<String, String> fruitDetails = new HashMap();
fruitDetails.put("Mango", "Mango is a delicious fruit!");
fruitDetails.put("Guava" "Guava is a delicious fruit!");
fruitDetails.put("Pineapple", "Pineapple is a delicious fruit!");
Map<String, String> fruitDetails2 = new HashMap();
fruitDetails2.put("Orange", "Orange is a delicious fruit!");
fruitDetails2.put("Banana" "Banana is a delicious fruit!");
fruitDetails2.put("Apple", "Apple is a delicious fruit!");
// STEP 2: Create a numeric key based HashMap containing fruitDetails so we can access them by index
Map<Integer, Map<String, String>> hashMap = new HashMap();
hashMap.put(0, fruitDetails);
hashMap.put(1, fruitDetails2);
// Now we can successfully access the fruitDetails by index like this
String fruit1 = hashMap.get(0).get("Guava");
String fruit2 = hashMap.get(1).get("Apple");
System.out.println(fruit1); // outputs: Guava is a delicious fruit!
System.out.println(fruit2); // outputs: Apple is a delicious fruit!
Try this:
myhashmap.entrySet()
.forEach{
println(it.getKey())
println(it.getValue())
}
或者如果你想通過索引
myhashmap.entrySet()[0].getKey()
myhashmap.entrySet()[0].getValue()
myhashmap.entrySet()[1].getKey()
myhashmap.entrySet()[1].getValue()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.