Java HashMap:如何通过索引获取键和值?

发布于 2024-09-28 04:45:15 字数 398 浏览 2 评论 0 原文

我正在尝试使用 HashMap 将唯一字符串映射到字符串 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
    }
}

有没有一种简单的方法可以做到这一点?

I am trying to use a HashMap to map a unique string to a string ArrayList like this:

HashMap<String, ArrayList<String>>

Basically, I want to be able to access the keys by number, not by using the key's name. And I want to be able to access said key's value, to iterate over it. I'm imagining something like this:

for(all keys in my hashmap) {
    for(int i=0; i < myhashmap.currentKey.getValue.size(); i++) {
        // do things with the hashmaps elements
    }
}

Is there an easy way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

谈情不如逗狗 2024-10-05 04:45:15

如果您确实只想要第一个键的值,那么这是通用解决方案

Object firstKey = myHashMap.keySet().toArray()[0];
Object valueForFirstKey = myHashMap.get(firstKey);

Here is the general solution if you really only want the first key's value

Object firstKey = myHashMap.keySet().toArray()[0];
Object valueForFirstKey = myHashMap.get(firstKey);
土豪我们做朋友吧 2024-10-05 04:45:15

您可以通过调用map.keySet()来迭代键,或者通过调用map.entrySet()来迭代条目。迭代条目可能会更快。

for (Map.Entry<String, List<String>> entry : map.entrySet()) {
    List<String> list = entry.getValue();
    // Do things with the list
}

如果您想确保按照插入键的相同顺序迭代键,请使用 LinkedHashMap

顺便说一句,我建议将映射的声明类型更改为 >。最好总是根据接口而不是实现来声明类型。

You can iterate over keys by calling map.keySet(), or iterate over the entries by calling map.entrySet(). Iterating over entries will probably be faster.

for (Map.Entry<String, List<String>> entry : map.entrySet()) {
    List<String> list = entry.getValue();
    // Do things with the list
}

If you want to ensure that you iterate over the keys in the same order you inserted them then use a LinkedHashMap.

By the way, I'd recommend changing the declared type of the map to <String, List<String>>. Always best to declare types in terms of the interface rather than the implementation.

背叛残局 2024-10-05 04:45:15

HashMap 不是有序的,除非您使用 LinkedHashMapSortedMap。在这种情况下,您可能需要一个 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 是一种保持顺序的特殊情况。

HashMaps are not ordered, unless you use a LinkedHashMap or SortedMap. In this case, you may want a LinkedHashMap. This will iterate in order of insertion (or in order of last access if you prefer). In this case, it would be

int index = 0;
for ( Map.Entry<String,ArrayList<String>> e : myHashMap.iterator().entrySet() ) {
    String key = e.getKey();
    ArrayList<String> val = e.getValue();
    index++;
}

There is no direct get(index) in a map because it is an unordered list of key/value pairs. LinkedHashMap is a special case that keeps the order.

美煞众生 2024-10-05 04:45:15

Kotlin HashMap 解答

您可以通过索引获取键。然后通过key获取value。

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.

Kotlin HashMap Answer

You can get key by index. Then get value by 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.
一指流沙 2024-10-05 04:45:15

您可以这样做:

for(String key: hashMap.keySet()){
    for(String value: hashMap.get(key)) {
        // use the value here
    }
}

这将迭代每个键,然后迭代与每个键关联的列表中的每个值。

You can do:

for(String key: hashMap.keySet()){
    for(String value: hashMap.get(key)) {
        // use the value here
    }
}

This will iterate over every key, and then every value of the list associated with each key.

抹茶夏天i‖ 2024-10-05 04:45:15

已经选择了解决方案。但是,我为那些想要使用替代方法的人发布此解决方案:

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

A solution is already selected. However, I post this solution for those who want to use an alternative approach:

// 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();
}
烈酒灼喉 2024-10-05 04:45:15
for (Object key : data.keySet()) {
    String lKey = (String) key;
    List<String> list = data.get(key);
}
for (Object key : data.keySet()) {
    String lKey = (String) key;
    List<String> list = data.get(key);
}
别想她 2024-10-05 04:45:15

我遇到了同样的问题,阅读了不同相关问题的几个答案,并提出了我自己的课程。

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 处于不同的状态。

I came across the same problem, read a couple of answers from different related questions and came up with my own class.

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

Example (types are differing from OPs question just for clarity):

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

Keep in mind that it does not override any of the complex methods, so you will need to do this on your own if you want to reliably access one of these.

Edit: I made a change to the putAll() method, because the old one had a rare chance to cause HashMap and LinkedList being in different states.

翻了热茶 2024-10-05 04:45:15

HashMap 不会按特定顺序保存键/值对。它们根据每个键从其 Object.hashCode() 方法返回的哈希值进行排序。但是,您可以使用迭代器来迭代键/值对集:

for (String key : hashmap.keySet()) 
{
    for (list : hashmap.get(key))
    {
        //list.toString()
    }
}

HashMaps don't keep your key/value pairs in a specific order. They are ordered based on the hash that each key's returns from its Object.hashCode() method. You can however iterate over the set of key/value pairs using an iterator with:

for (String key : hashmap.keySet()) 
{
    for (list : hashmap.get(key))
    {
        //list.toString()
    }
}
浅忆流年 2024-10-05 04:45:15

如果您不关心实际的键,迭代 Map 的所有值的一种简洁方法是使用其 values() 方法

Map<String, List<String>> myMap;

for ( List<String> stringList : myMap.values() ) {
    for ( String myString : stringList ) {
        // process the string here
    }
}

values( ) 方法是 Map 接口的一部分,返回地图中值的 Collection 视图。

If you don't care about the actual key, a concise way to iterate over all the Map's values would be to use its values() method

Map<String, List<String>> myMap;

for ( List<String> stringList : myMap.values() ) {
    for ( String myString : stringList ) {
        // process the string here
    }
}

The values() method is part of the Map interface and returns a Collection view of the values in the map.

一世旳自豪 2024-10-05 04:45:15

例如,您需要像这样创建多个 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!

You'll need to create multiple HashMaps like this for example

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!
婴鹅 2024-10-05 04:45:15

您可以使用 Kotlin 扩展函数

fun LinkedHashMap<String, String>.getKeyByPosition(position: Int) =
        this.keys.toTypedArray()[position]


fun LinkedHashMap<String, String>.getValueByPosition(position: Int) =
        this.values.toTypedArray()[position]

You can use Kotlin extension function

fun LinkedHashMap<String, String>.getKeyByPosition(position: Int) =
        this.keys.toTypedArray()[position]


fun LinkedHashMap<String, String>.getValueByPosition(position: Int) =
        this.values.toTypedArray()[position]
简单爱 2024-10-05 04:45:15

试试这个:

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

Try this:

myhashmap.entrySet()
           .forEach{
               println(it.getKey())
               println(it.getValue())
           }

or if you want by index

myhashmap.entrySet()[0].getKey()
myhashmap.entrySet()[0].getValue()

myhashmap.entrySet()[1].getKey()
myhashmap.entrySet()[1].getValue()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文