How to count the number of occurrences of an element in a List

后端 未结 22 1156
一生所求
一生所求 2020-11-22 12:25

I have an ArrayList, a Collection class of Java, as follows:

ArrayList animals = new ArrayList();
animals.add(\"bat\         


        
相关标签:
22条回答
  • 2020-11-22 12:29

    I wonder, why you can't use that Google's Collection API with JDK 1.6. Does it say so? I think you can, there should not be any compatibility issues, as it is built for a lower version. The case would have been different if that were built for 1.6 and you are running 1.5.

    Am I wrong somewhere?

    0 讨论(0)
  • 2020-11-22 12:29

    A slightly more efficient approach might be

    Map<String, AtomicInteger> instances = new HashMap<String, AtomicInteger>();
    
    void add(String name) {
         AtomicInteger value = instances.get(name);
         if (value == null) 
            instances.put(name, new AtomicInteger(1));
         else
            value.incrementAndGet();
    }
    
    0 讨论(0)
  • 2020-11-22 12:30

    This shows, why it is important to "Refer to objects by their interfaces" as described in Effective Java book.

    If you code to the implementation and use ArrayList in let's say, 50 places in your code, when you find a good "List" implementation that count the items, you will have to change all those 50 places, and probably you'll have to break your code ( if it is only used by you there is not a big deal, but if it is used by someone else uses, you'll break their code too)

    By programming to the interface you can let those 50 places unchanged and replace the implementation from ArrayList to "CountItemsList" (for instance ) or some other class.

    Below is a very basic sample on how this could be written. This is only a sample, a production ready List would be much more complicated.

    import java.util.*;
    
    public class CountItemsList<E> extends ArrayList<E> { 
    
        // This is private. It is not visible from outside.
        private Map<E,Integer> count = new HashMap<E,Integer>();
    
        // There are several entry points to this class
        // this is just to show one of them.
        public boolean add( E element  ) { 
            if( !count.containsKey( element ) ){
                count.put( element, 1 );
            } else { 
                count.put( element, count.get( element ) + 1 );
            }
            return super.add( element );
        }
    
        // This method belongs to CountItemList interface ( or class ) 
        // to used you have to cast.
        public int getCount( E element ) { 
            if( ! count.containsKey( element ) ) {
                return 0;
            }
            return count.get( element );
        }
    
        public static void main( String [] args ) { 
            List<String> animals = new CountItemsList<String>();
            animals.add("bat");
            animals.add("owl");
            animals.add("bat");
            animals.add("bat");
    
            System.out.println( (( CountItemsList<String> )animals).getCount( "bat" ));
        }
    }
    

    OO principles applied here: inheritance, polymorphism, abstraction, encapsulation.

    0 讨论(0)
  • 2020-11-22 12:33

    Simple Way to find the occurrence of string value in an array using Java 8 features.

    public void checkDuplicateOccurance() {
            List<String> duplicateList = new ArrayList<String>();
            duplicateList.add("Cat");
            duplicateList.add("Dog");
            duplicateList.add("Cat");
            duplicateList.add("cow");
            duplicateList.add("Cow");
            duplicateList.add("Goat");          
            Map<String, Long> couterMap = duplicateList.stream().collect(Collectors.groupingBy(e -> e.toString(),Collectors.counting()));
            System.out.println(couterMap);
        }
    

    Output : {Cat=2, Goat=1, Cow=1, cow=1, Dog=1}

    You can notice "Cow" and cow are not considered as same string, in case you required it under same count, use .toLowerCase(). Please find the snippet below for the same.

    Map<String, Long> couterMap = duplicateList.stream().collect(Collectors.groupingBy(e -> e.toString().toLowerCase(),Collectors.counting()));
    

    Output : {cat=2, cow=2, goat=1, dog=1}

    0 讨论(0)
  • 2020-11-22 12:36

    In Java 8:

    Map<String, Long> counts =
        list.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting()));
    
    0 讨论(0)
  • 2020-11-22 12:36

    If you are a user of my ForEach DSL, it can be done with a Count query.

    Count<String> query = Count.from(list);
    for (Count<Foo> each: query) each.yield = "bat".equals(each.element);
    int number = query.result();
    
    0 讨论(0)
提交回复
热议问题