0

Edit: I notice that it is possible to use hashset to stop duplicate elements, however, I don't think using that can count the duplicate elements, please correct me if I am wrong.

I'm trying to store items in an array list. Then after storing, scan through for duplicates and mark how many of each unique duplicate there is. I tried to use a nested for loop to scan through an arraylist for each element, and comparing it to every other item, however, it didn't remove duplicates correctly or keep track of the number of duplicates correctly.

ArrayList<Integer> itemQuantity = new ArrayList<Integer>();
        for(int i = 0; i < array.size(); i++) {
            int quantity = 1;
            for(int j = 1; j < array.size(); j++) {
                if(array.get(j).equalsIgnoreCase(array.get(i))) {
                    array.remove(j);
                    quantity++;
                }

            }
            itemQuantity.add(quantity);
        }

This is what I had. I am open to answering any questions about my code and sorry if I'm unclear. This is my first time using this website.

I made arraylist itemQuantity to store the amounts of duplicates for each unique element. Then first for loop is checking through each element, then nested for loop is comparing it to every other element, if an element is the same as another, remove it from the list and increase one to the duplicate count.

etn
  • 1
  • 2
  • What is `unique duplicate`? – Arvind Kumar Avinash Oct 25 '20 at 15:43
  • 1
    If you don't want to store duplicates use Set instead of List. If you want to generate Element->repetition mapping you can use something like `Map map = yourList.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));`. – Pshemo Oct 25 '20 at 15:49
  • What I mean by that is for example if I have in my arraylist [car, car, truck, truck, truck, donkey]. Car and truck would be unique duplicates because they are different elements with duplicates. Hope this is more clear! – etn Oct 25 '20 at 15:50
  • Sorry, I am still very beginner at Java. I don't really know what element repetition mapping is. – etn Oct 25 '20 at 15:53
  • The question was originally closed as a duplicate of: https://stackoverflow.com/questions/203984/how-do-i-remove-repeated-elements-from-arraylist, I reopened the question because I didn't see anything in the posting that addresses the requirement to **keep track of the number of duplicates**. – camickr Oct 25 '20 at 16:04

0 Answers0