java_enthu
java_enthu

Reputation: 2327

Finding number of occurance of an element in a list

Is there a direct way to find out if the list contains duplicates? Direct API method in some third party utils? And if the list contains duplicates how many such duplicate elements exist in the list? Code we can write but I want to know if any direct API exists?

Upvotes: 0

Views: 3018

Answers (6)

MirroredFate
MirroredFate

Reputation: 12826

It looks like you want something like this:

public int getNumOfElementInList(List<Object> myList, Object myElement){
   int count = 0;
   for(Object element: myList){
      if(element.equals(myElement)) //or use instanceof instead, depending
         count++;
   }
   return count;
}

This will give you the number of an element in a list. Alternatively, you could make a List instead of using count, and add the duplicate elements to the List, and return that.

Such as:

public List<DuplicateStats> getTotalNumOfElementInList(List<Object> myList){
   List<DuplicateStats> dups = new ArrayList<DuplicateStats>();
   int i;
   for(Object element: myList){
      if((i = dups.indexOf(element) != -1)
         dups.get(i).addOne();
      else
         List.add(new DuplicateStats(element));
   }
   return count;
}

public class DuplicateStats {
   private Object element;
   private int count;

   public DuplicateStats(Object o){
        element = o;
   }

   public boolean equals(String compare){
        return element.toString.equals(compare);
   }

   public void addOne(){
       count++;
   }
}

You can add getters, setters, etc. to the class DuplicateStats, but it will keep track of duplicates for you.

Upvotes: 2

Simeon
Simeon

Reputation: 7792

If you want an API you can find duplicates with Guava's Multiset.

Just add your list do the set and use the count method.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533530

You can count occurrences with

List<T> list =
Map<T, Integer> count = new HashMap<T,Integer>();
for(T t: list) {
   Integer i = count.get(t);
   if (i ==  null) i = 0;
   count.put(t, i + 1);
}

Upvotes: 4

Jeff Foster
Jeff Foster

Reputation: 44706

If you want to find out how many duplicates there are you could keep the list with duplicates, together with a set without duplicates. The number of duplicates is then just the size of the list minus the size of the set.

Upvotes: 1

Jacek L.
Jacek L.

Reputation: 1416

There are no built-in methods to do this. However you can use LinkedHashSet for example to solve this problem. It does not allow duplicates (as it acts like a set) but it preserves an order of elements (as it acts like a list). You can iterate over all of elements from your list and add them to LinkedHashSet, checking if add method returns true or false.

Upvotes: 0

talnicolas
talnicolas

Reputation: 14053

No you'll have to do it by yourself. But you can use objects that won't allow to insert duplicate data (here)

Upvotes: 2

Related Questions