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

Java HashMap:如何通过索引获取键和值?,java,iteration,hashmap,Java,Iteration,Hashmap,我尝试使用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 } } HashMa

我尝试使用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
    }
}
HashMap
基本上,我希望能够通过数字访问密钥,而不是使用密钥的名称。我希望能够访问该键的值,并对其进行迭代。我在想象这样的事情:

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
    }
}
for(我的hashmap中的所有键){
对于(int i=0;i

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

除非您使用
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++;
}
int索引=0;
对于(Map.Entry e:myHashMap.iterator().entrySet()){
String key=e.getKey();
ArrayList val=e.getValue();
索引++;
}
映射中没有直接获取(索引),因为它是键/值对的无序列表
LinkedHashMap
是维持订单的特殊情况。

您可以执行以下操作:

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

这将遍历每个键,然后遍历与每个键关联的列表的每个值。

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

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

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

for (Map.Entry<String, List<String>> entry : map.entrySet()) {
    List<String> list = entry.getValue();
    // Do things with the list
}
for(Map.Entry:Map.entrySet()){
List=entry.getValue();
//按清单做事
}
如果要确保按插入键的相同顺序迭代键,请使用
LinkedHashMap

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

for(对象键:data.keySet()){
for (Object key : data.keySet()) {
    String lKey = (String) key;
    List<String> list = data.get(key);
}
字符串lKey=(字符串)键; 列表=data.get(键); }
如果您真的只需要第一个键的值,这里有一个通用的解决方案

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

如果您不关心实际的键,那么迭代所有映射值的简洁方法是使用其
values()
方法

Map<String, List<String>> myMap;

for ( List<String> stringList : myMap.values() ) {
    for ( String myString : stringList ) {
        // process the string here
    }
}
Map-myMap;
对于(List-stringList:myMap.values()){
for(字符串myString:stringList){
//在这里处理字符串
}
}

values()
方法是映射界面的一部分,返回映射中值的集合视图。

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

// 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();
}
//如果您想从hashmap中读取值的顺序与放入值的顺序相同,请使用LinkedHashMap
私有ArrayList getMapValueAt(LinkedHashMap hashMap,int索引)
{
Map.Entry=(Map.Entry)hashMap.entrySet().toArray()[index];
返回条目.getValue();
}

您可以使用Kotlin扩展功能

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


fun LinkedHashMap<String, String>.getValueByPosition(position: Int) =
        this.values.toTypedArray()[position]
fun LinkedHashMap.getKeyByPosition(位置:Int)=
this.keys.toTypedArray()[position]
有趣的LinkedHashMap.getValueByPosition(位置:Int)=
this.values.toTypedArray()[position]

我遇到了同样的问题,从不同的相关问题中读了一些答案,然后想出了我自己的课程

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;
    }
}
公共类IndexableMap扩展HashMap{
私有LinkedList键列表=新LinkedList();
@凌驾
公共V输入(K键,V值){
如果(!keyList.contains(key))
keyList.add(key);
返回super.put(键、值);
}
@凌驾

public void putAll(Map例如,您需要创建多个这样的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!
Map fruitDetails=newhashmap();
水果细节。放(“芒果”,“芒果是一种美味的水果!”);
水果细节。把(“番石榴”“番石榴是一种美味的水果!”);
水果细节。放入(“菠萝”,“菠萝是一种美味的水果!”);
Map fruitDetails2=新的HashMap();
水果细节2.把(“橘子”,“橘子是一种美味的水果!”);
水果的细节2.放(“香蕉”“香蕉是一种美味的水果!”);
水果细节2.把(“苹果”,“苹果是一种美味的水果!”);
//步骤2:创建一个基于数字键的HashMap,其中包含水果细节,以便我们可以通过索引访问它们
Map hashMap=新hashMap();
hashMap.put(0,详细信息);
hashMap.put(1,2);
//现在我们可以通过这样的索引成功地访问水果细节
字符串fruit1=hashMap.get(0.get(“番石榴”);
字符串fruit2=hashMap.get(1.get(“苹果”);
System.out.println(水果1);//输出:番石榴是一种美味的水果!
System.out.println(水果2);//输出:苹果是一种美味的水果!

Kotlin HashMap答案

您可以按索引获取键,然后按键获取值

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.
val item=HashMap()//伪HashMap。
val keyByIndex=item.keys.elementAt(0)//按索引获取键。我选择了“0”。
val valueOfElement=item.getValue(keyByIndex)//获取值。

感谢所有回答的人。jjngguy,这正是我想要的。你也是,kkress。好吧,非常严格……OP要求的是值,而不是键。因此你可能需要添加
Object myValue=myMap.get(myKey);
我不确定
toArray()
的(潜在)开销是否超过
迭代器()。next()
…如果希望“仅”第一个元素,请参阅