遍历HashMap中的ArrayList



我有以下HashMap:

HashMap<Integer, ArrayList<Integer>> mat = new HashMap<Integer, ArrayList<Integer>>();

看起来像这样:

1: [2, 3]
2: [1, 4, 5]
3: [1, 6, 7]

我的问题是:

  1. 如何在HashMap的第I个条目中获得ArrayList的大小

  2. 如何访问数组列表中给定键的第I个元素?

如何在HashMap的第I个条目中获得数组列表的大小?

我假设您指的是键为i的条目。(由于HashMap的元素是无序的,所以讨论HashMap的第i项是没有意义的。)

   ArrayList<Integer> tmp = mat.get(i);
   if (tmp != null) {
       System.out.println("The size is " + tmp.size());
   }

如何访问数组列表中给定键的第I个元素?

我假设您希望对数组

进行正常的(对于Java)从零开始的索引。
   ArrayList<Integer> tmp = mat.get(key);
   if (tmp != null && i >= 0 && i < tmp.size()) {
       System.out.println("The element is " + tmp.get(i));
   }

注意,如果想避免异常,需要处理各种边缘情况。(我已经处理过了……)

如何在HashMap的第I个条目中获得数组列表的大小?


如果i不是你的HashMap的key,恐怕我们不能直接得到HashMap的i-th entry

Hashmap可以包含空值,因此您需要在使用arraylistsize()get(i)之前进行null检查。

1)如何获得HashMap中第I个条目的数组列表的大小

ArrayList<Integer> list = mat.get(i);
if(list != null) {
   list.size(); //gives the size of the list
}

2)如何访问数组列表中给定键的第I个元素?

    ArrayList<Integer> list = mat.get(i);
    if(list != null) {
       list.get(i);//gives the i-th element from list
   }

你可以参考这里和这里

最新更新