开发者

Finding number of occurance of an element in a list

开发者 https://www.devze.com 2023-03-13 16:22 出处:网络
Is there a direct way to find out if the list contains duplicates? Direct API method in some third party utils?

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 开发者_JAVA百科API exists?


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


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


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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消