【问题标题】:how can we iterate in ArrayList inside HashMap?我们如何在 HashMap 中的 ArrayList 中进行迭代?
【发布时间】:2019-04-05 04:16:11
【问题描述】:

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

HashMap> hash=new HashMap>(); // 现在我想遍历 HashMap 中特定键的数组列表

如果用户输入 1(即 Key),那么输出应该是 一个 乙 C D

如果用户输入 2(即 Key),那么输出应该是 乙 F G H

【问题讨论】:

    标签: arraylist hashmap


    【解决方案1】:

    我不太确定,我明白了你的问题,但如果你想遍历一个键数组并在哈希图中查找与这些键对应的所有值,你可以这样做(假设问题是在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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-08
      • 2016-02-03
      • 2011-01-08
      • 2011-12-02
      • 2021-07-31
      • 2017-11-01
      • 1970-01-01
      相关资源
      最近更新 更多