简体   繁体   中英

Counting keys in LinkedHashMap<String, ArrayList<String>>

Let's say I have something like this:

LinkedHashMap <String, ArrayList<String>> h 
keyOne has
stringOne 
stringTwo 
stringThree

keyTwo has
stringOne

How do I count the size of ArrayList of the associated key? So for keyOne, it should give me 3.

Did you try:

ArrayList<String> tmp = h.get("keyOne");
if ( tmp != null ) {
    return tmp.size();
} else {
    return 0;
}

You can just write h.get(key).size()

int count = h.get("keyOne").size();

should do it.

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Set;

public class Test {
    public static void main(String[] args) {
        LinkedHashMap<String, ArrayList<String>> h = new LinkedHashMap<String, ArrayList<String>>();
        ArrayList<String> al1 = new ArrayList<String>();
        al1.add("Value11");
        al1.add("Value12");
        al1.add("Value13");
        ArrayList<String> al2 = new ArrayList<String>();
        al2.add("Value21");
        h.put("key1", al1);
        h.put("key2", null);
        Set<String> set = h.keySet();
        for (String key : set) {
            ArrayList<String> al = h.get(key);
            if (al != null)
                System.out.println (key + " : " + al.size());
            else
                System.out.println (key + " is empty ");
        } 
    }
}

Output:

key1 : 3
key2 is empty 

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