如何在添加新项目时启动计数器

时间:2015-08-31 13:02:09

标签: java arrays counter

我有如下所示的数组

public static void main(String[] args) {
    List asList = Arrays.asList("banner","carousel","banner","carousel","banner");
    Set<String> mySet = new HashSet<String>(asList);
    for(String s: mySet){

     System.out.println(s + " " +Collections.frequency(asList,s));

    }

}

输出:

carousel 2
banner 3

DesiredOutput:

banner0
carousel0
banner1
carousel1
banner2

请告诉我在这种情况下需要做些什么。

4 个答案:

答案 0 :(得分:1)

你需要做出这个简单的改变:这里我们做一个子列表,它只计算当前的循环项目。

public static void main(String[] args) {
        List asList = Arrays.asList("banner", "carousel", "banner", "carousel", "banner");
        for(int i=0;i<asList.size();i++) {
            System.out.println(asList.get(i)+" : " + Collections.frequency(asList.subList(0,i), asList.get(i)));
        }
    }

输出:

banner : 0
carousel : 0
banner : 1
carousel : 1
banner : 2

答案 1 :(得分:0)

您可以在添加:

之前简单地包装add方法以打印频率写入
List<String> asList = Arrays.asList("banner", "carousel", "banner", "carousel", 
                                   "banner");
// ...
Set<String> mySet = new HashSet<>();
for(String s : asList) {
    addAndPrint(s, mySet);
}

private static final addAndPrint(String s, Collectection<String> c) {
    System.out.println(s + " " + Collections.frequency(c, s));
    c.add(s);
}

答案 2 :(得分:0)

可以使用Map:

来实现
   public static void main(String[] args)
    {
        final List<String> asList = Arrays.asList("banner", "carousel", "banner", "carousel", "banner");
        final Map<String, Integer> map = new HashMap<String, Integer>();

        for (final String s : asList)
        {

            if (!map.containsKey(s))
            {
                map.put(s, 0);
            }
            else
            {
                map.put(s, map.get(s) + 1);
            }
            System.out.println(s + " " + map.get(s));
        }

    }

答案 3 :(得分:-1)

尝试使用iterator和std for循环而不是cutom set。如果你总是有&#34; Carousel&#34;和#34; Banner&#34;然后声明两个计数器,并在遇到每个计数器时遇到它们。以下是一个片段

 List asList = Arrays.asList("banner","carousel","banner","carousel","banner");
        int countb = 0;
        int countc = 0;
        for (int i = 0; i < asList.size(); i++) {
            if (asList.get(i).equals("banner")) {
                countb++;
                System.out.print("banner"+countb+"\n");
            } else if (asList.get(i).equals("carousel")) {
                countc++;
                System.out.print("carousel"+countc+"\n");

            }
        }