简体   繁体   中英

Iterating through an ArrayList in a HashMap

I have the following 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 ?

  2. How do I access the i-th element in my ArrayList on a given key?

How do I get the size of the ArrayList in the i-th entry of my HashMap ?

I assume that you mean the entry whose key is i . (Since the elements of a HashMap are not ordered, it is not meaningful to talk about the i-th entry of a HashMap .)

   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?

I assume that you want normal (for Java) zero-based indexing of the array

   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 ?


if the i is not a key of your HashMap, I'm afraid that we cant get the i-th entry of HashMap directly.

Hashmap can contain null values, so you need to do the null check before using the size() and get(i) of the arraylist .

1) How do I get the size of the ArrayList in the i-th entry of my HashMap ?

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?

    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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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