Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initiate counter when new item is added

I have array as seen below

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));

    }

}

Output:

carousel 2
banner 3

DesiredOutput:

banner0
carousel0
banner1
carousel1
banner2

Please let me know what needs to be done in this case.

like image 566
Manan Kapoor Avatar asked Jan 17 '26 04:01

Manan Kapoor


1 Answers

You need to make this simple change : here we do a sub list which counts only till the current loop item.

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)));
        }
    }

Output :

banner : 0
carousel : 0
banner : 1
carousel : 1
banner : 2
like image 145
StackFlowed Avatar answered Jan 19 '26 20:01

StackFlowed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!