循环遍历数组并在满足特定条件时显示项目

时间:2014-08-03 03:17:28

标签: java

我不知道为什么这需要我这么长时间才能搞清楚,但我有一个我希望循环的HashMaps的ArrayList。循环部分很容易,我知道如何做,但我只想在符合特定条件时显示项目。

以下是我HashMap<String, String>中的内容示例:

post_type="Facebook" 
post_type="Facebook" 
post_type="Twitter"

这是我试图循环上述内容的代码。打印时,它只打印一行而不是两行。

    for (int i=0; i < newArray.size(); i++)
    {
        String postType = newArray.get(i).get("type"); 

        if (postType.equals("Facebook")){ 
            System.out.println("HELLO"); // i want this to print twice, but it only prints once, even though there are two elements of type Facebook in the HashMap
        }
    }

2 个答案:

答案 0 :(得分:1)

查看您的代码,

String postType = newArray.get(i).get("type"); 

应该是

String postType = newArray.get(i).get("post_type"); 

由于

  

...我有一个ArrayList HashMap ...这是我HashMap<String, String>内的内容示例:

post_type="Facebook" 
post_type="Facebook" 
post_type="Twitter"

并且,type不是post_type

答案 1 :(得分:0)

我认为你需要保持像

这样的东西
Map<String,ArrayList<String>> map = new HashMap<String,ArrayList<String>>();

为单个键维护多个值。 您的案例中的关键是&#34; post_type&#34;和价值是Facebook,Facebook,Twitter