【问题标题】:Loop through an ArrayList of HashMaps Java循环遍历 HashMaps Java 的 ArrayList
【发布时间】:2013-04-05 11:32:11
【问题描述】:
ArrayList<HashMap<String, Integer>> myList = new ArrayList<HashMap<String, Integer>>();

    HashMap<String, Integer> check = new HashMap<String, Integer>();

我的数组列表中有一些哈希图,我想比较哈希图的重复项,例如 0,1 0,2 0,3 0,4....1,2 1,3 1,4。 ....2,3 2,4 等

我正在做一个嵌套的 for 循环,但被困在如何访问哈希图上并尝试了这个

for (int a =0; a<myList.size();a++){
            for(int b=a+1; b<myList.size();b++){
                for (String key : myList[a].check.keySet())
            }
        }

但这不起作用。如果它们在数组列表中,我如何访问我的哈希图的所有键?我怎样才能做到这一点?

【问题讨论】:

  • @BalaR: ArrayList 不能用方括号括起来。

标签: java arraylist hashmap


【解决方案1】:

这是一个迭代的例子。我创建了虚拟数据来测试代码

private void ArrayListAndHashMap()
    {
        ArrayList<HashMap<String, Integer>> myList = new ArrayList<HashMap<String, Integer>>();


        HashMap<String, Integer> data1 = new HashMap<String, Integer>();
         data1.put("0",new Integer(1));
         data1.put("1",new Integer(2));
         data1.put("2",new Integer(3));
         data1.put("3",new Integer(4));

        HashMap<String, Integer> data2 = new HashMap<String, Integer>();
        data1.put("10",new Integer(10));
         data1.put("11",new Integer(20));
         data1.put("12",new Integer(30));
         data1.put("13",new Integer(40));

         myList.add(data1);
         myList.add(data2);


        for (int a =0; a<myList.size();a++)
        {
            HashMap<String, Integer> tmpData = (HashMap<String, Integer>) myList.get(a);
            Set<String> key = tmpData.keySet();
            Iterator it = key.iterator();
            while (it.hasNext()) {
                String hmKey = (String)it.next();
                Integer hmData = (Integer) tmpData.get(hmKey);

                System.out.println("Key: "+hmKey +" & Data: "+hmData);
                it.remove(); // avoids a ConcurrentModificationException
            }

        }       
    }

输出是

Key: 3 & Data: 4
Key: 2 & Data: 3
Key: 10 & Data: 10
Key: 1 & Data: 2
Key: 0 & Data: 1
Key: 13 & Data: 40
Key: 11 & Data: 20
Key: 12 & Data: 30

【讨论】:

    【解决方案2】:

    [] 运算符只能用于数组。 List 有一个get(int index) 方法来获取给定索引处的元素:

    for (String key : myList.get(a).keySet()) {
        ...
    }
    

    记录了 Java 类:http://docs.oracle.com/javase/6/docs/api/

    【讨论】:

    • 您可能还想更改声明 myList 的方式: List> myList = new ArrayList>();
    • @vtheron 如果只是List,那么应该使用Iterator而不是直接索引;如果List 恰好是LinkedList,则索引会很慢。
    • 你能更新 Java 8 吗?
    猜你喜欢
    • 2014-03-22
    • 2020-06-15
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    • 2013-12-26
    相关资源
    最近更新 更多