让我说我有这样的事情:
LinkedHashMap <String, ArrayList<String>> h
keyOne has
stringOne
stringTwo
stringThree
keyTwo has
stringOne
如何计算关联键的ArrayList的大小?所以对于keyOne,它应该给我3个。
答案 0 :(得分:5)
你有没有尝试过:
ArrayList<String> tmp = h.get("keyOne");
if ( tmp != null ) {
return tmp.size();
} else {
return 0;
}
答案 1 :(得分:2)
你可以写h.get(key).size()
答案 2 :(得分:2)
int count = h.get("keyOne").size();
应该这样做。
答案 3 :(得分:2)
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 ");
}
}
}
输出:
key1 : 3
key2 is empty