首页 > 解决方案 > 我们如何在 HashMap 中的 ArrayList 中进行迭代?

问题描述

我想分别打印 ArrayList 中的每个值,即 {1=[A, B,C, D], 2=[E, F, G, H]}

哈希映射>哈希=新哈希映射>(); // 现在我想遍历 HashMap 中特定键的数组列表

如果用户输入 1(即 Key),则输出应为 A B C D

如果用户输入 2(即 Key),则输出应为 E F G H

标签: arraylisthashmap

解决方案


我不太确定,我得到了你的问题,但是如果你想遍历一个键数组并在哈希图中查找与这些键对应的所有值,你可以做这样的事情(假设问题在 java 中) :

import java.util.*;

class Main {
  public static HashMap<Integer, String[]> hmap = new HashMap<Integer, String[]>();
  public static int[] arrToTraverse = {1,2};

  public static void main(String[] args) {
    String[] s1 = {"A", "B", "C", "D"};
    String[] s2 = {"E", "F", "G", "H"};
    hmap.put(1, s1);
    hmap.put(2, s2);
    for(int no : arrToTraverse) {
      System.out.println(Arrays.toString(getValue(no)));
    }
  }

  public static String[] getValue(int key) {
    return hmap.get(key); 
  }
}

这将输出:

[A, B, C, D]
[E, F, G, H]

推荐阅读