简体   繁体   English

遍历HashMap中的ArrayList

[英]Iterating through an ArrayList in a HashMap

I have the following HashMap: 我有以下HashMap:

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

which looks like this: 看起来像这样:

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

My questions are: 我的问题是:

  1. How do I get the size of the ArrayList in the i-th entry of my HashMap ? 如何在HashMap的第i个条目中获取ArrayList的大小?

  2. How do I access the i-th element in my ArrayList on a given key? 如何在给定键上访问ArrayList中的第i个元素?

How do I get the size of the ArrayList in the i-th entry of my HashMap ? 如何在HashMap的第i个条目中获取ArrayList的大小?

I assume that you mean the entry whose key is i . 我假设您的意思是键为i的条目。 (Since the elements of a HashMap are not ordered, it is not meaningful to talk about the i-th entry of a HashMap .) (由于HashMap的元素没有排序,因此谈论HashMap的第i个条目没有意义。)

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

How do I access the i-th element in my ArrayList on a given key? 如何在给定键上访问ArrayList中的第i个元素?

I assume that you want normal (for Java) zero-based indexing of the array 我假设您想要数组的常规(对于Java)基于零的索引

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

Note that there are various edge-cases that need to be dealt with if you want to avoid exceptions. 请注意,如果要避免出现异常,需要处理各种边缘情况 (I have dealt with them ...) (我已经处理过了……)

How do I get the size of the ArrayList in the i-th entry of my HashMap ? 如何在HashMap的第i个条目中获取ArrayList的大小?


if the i is not a key of your HashMap, I'm afraid that we cant get the i-th entry of HashMap directly. 如果i不是您的HashMap的key ,恐怕我们无法直接获取HashMap i-th entry

Hashmap can contain null values, so you need to do the null check before using the size() and get(i) of the arraylist . Hashmap可以包含空值,因此您需要在使用arraylistsize()get(i)之前进行null检查。

1) How do I get the size of the ArrayList in the i-th entry of my HashMap ? 1)如何获取HashMap的第i个条目中ArrayList的大小?

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

2) How do I access the i-th element in my ArrayList on a given key? 2)如何在给定键上访问ArrayList中的第i个元素?

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

You can refer here and here 您可以在这里这里参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM