How to count occurrence of an element in a List?

I'm pretty sure the static frequency-method in Collections would come in handy here: int occurrences = Collections. Frequency(animals, "bat") That's how I'd do it anyway. I'm pretty sure this is jdk 1.6 straight up.

I'm pretty sure the static frequency-method in Collections would come in handy here: int occurrences = Collections. Frequency(animals, "bat"); That's how I'd do it anyway. I'm pretty sure this is jdk 1.6 straight up.

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?

They have clearly mentioned that they are in the process of upgrading their api to jdk 1.6. – MM. Feb 3 '09 at 3:54 That doesn't make old incompatible. Does it?

– Adeel Ansari Feb 3 '09 at 4:04 It should not. But the way they were throwing disclaimers, makes me uncomfortable to use it in their 0.9 version – MM. Feb 3 '09 at 4:07 We use it with 1.6. Where does it say it is only compatible with 1.5?

– Patrick Feb 3 '09 at 21:21 1 By "upgrading to 1.6" they probably mean "upgrading to take advantage of new stuff in 1.6," not "fixing compatibility with 1.6". – Adam Jaskiewicz Feb 3 '09 at 22:01.

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 extends ArrayList { // This is private.It is not visible from outside.

Private Map count = new HashMap(); // 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 animals = new CountItemsList(); animals. Add("bat"); animals. Add("owl"); animals.

Add("bat"); animals. Add("bat"); System.out. Println( (( CountItemsList )animals).

GetCount( "bat" )); } } OO principles applied here: inheritance, polymorphism, abstraction, encapsulation.

1 Well one should always try composition rather than inheritance. Your implementation is now stuck to ArrayList when there may be times you want a LinkedList or other. Your example should have taken another LIst in its constructor/factory and returned a wrapper.

– mP. Feb 5 '09 at 2:59 I completely agree with you. The reason I used inheritance in the sample is because it is a lot more easier to show a running example using inheritance than composition ( having to implement the List interface ).

Inheritance creates the highest coupling. – OscarRyz Feb 5 '09 at 18:15.

There is no native method in Java to do that for you. However, you can use CollectionUtils#countMatches() from Apache Commons-Collections to do it for you.

Refer to my answer below - the correct answer is to use a structure that supports the counting idea from the begining rather than counting entries from start to end each time a query is made. – mP. Feb 3 '09 at 3:38 @mP So you just downvote everyone who has a different opinion than you?

What if he can't use a Bag for some reason or is stuck with using one of the native Collections? – Kevin Feb 3 '09 at 3:41 Doesn't deserve a downvote, IMHO. – Adeel Ansari Feb 3 '09 at 3:43 -1 for being a sore loser :-) I think mP downvoted you because your solution costs time every time you want a result.

A bag cost a little time only at insertion. Like databases, these sort of structures tend to be "more read than write" so it makes sense to use the low cost option. – paxdiablo Feb 3 '09 at 3:44 And it appears your answer also requires non-native stuff, so your comment seems a little strange.

– paxdiablo Feb 3 '09 at 3:45.

Sorry there's no simple method call that can do it. All you'd need to do though is create a map and count frequency with it. HashMap frequencymap = new HashMap(); foreach(String a in animals) { if(frequencymap.

ContainsKey(a)) { frequencymap. Put(a, frequencymap. Get(a)+1); } else{ frequencymap.

Put(a, 1); } }.

This is really not a scalable solution - imagine MM's data set had hundreds and thousands of entries and MM wanted to know the frequences for each and every entry. This could potentially be a very costly task - especially when there are much better ways to do it. – mP.

Feb 3 '09 at 3:37 Yes, it might not be a good solution, doesn't mean its wrong. – Adeel Ansari Feb 3 '09 at 3:44 He just wants the number of 'bat' occurrences. Just iterate once over the original ArrayList and increment a counter whenever you see 'bat'.

– Frank Feb 3 '09 at 4:29 @dehmann, I don't think he literally wants the number of bat occurrences in a 4-element collection, I think that was just sample data so we'd understand better :-). – paxdiablo Feb 3 '09 at 4:33 @Vinegar Just because it works doesn't mean its the proper way to do things. We could scan all the rows in a table and manually find the bat record but we don't we create the appropriate query.

– mP. Feb 3 '09 at 6:01.

What you want is a Bag - which is like a set but also counts the number of occurances. Unfortunately the java Collections framework - great as they are don't have a Bag impl. For that one must use the Apache Common Collection link text.

Best scalable solution and, if you can't use third-party stuff, just write your own. Bags aren't rocket science to create. +1.

– paxdiablo Feb 3 '09 at 3:47.

A slightly more efficient approach might be Map instances = new HashMap(); void add(String name) { AtomicInteger value = instances. Get(name); if (value == null) instances. Put(name, new AtomicInteger(1)); else value.incrementAndGet(); }.

So do it the old fashioned way and roll your own: Map instances = new HashMap(); void add(String name) { Integer value = instances. Get(name); if (value == null) { value = new Integer(0); instances. Put(name, value); } instances.

Put(name, value++); }.

With the appropriate "synchronized", if needed, to avoid race conditions. But I'd still prefer to see this in its own class. – paxdiablo Feb 3 '09 at 3:57 This code doesn't work.

See corrected code in subsequent answer. – joel. Neely Feb 3 '09 at 4:12 You have a typo.

Need HashMap instead, as you are taking it in Map. But the mistake to put 0 instead of 1 is a bit more serious. – Adeel Ansari Feb 3 '09 at 4:21 No offense intended; I didn't know how to contact you directly and couldn't fit the changes in a comment.

I'll delete my answer. – joel. Neely Feb 3 '09 at 13:52.

If you are a user of my ForEach DSL, it can be done with a Count query. Count query = Count. From(list); for (Count each: query) each.

Yield = "bat". Equals(each. Element); int number = query.result().

This is an example where C# shines compared to Java. In C#, you would need only do this: var count = (from a in animals where a. Value = "bat" select a).Count(); Unfortunately, Java doesn't have anything like Linq or lambda's, so your'e stuck doing it the interative way that others suggest.

Put the elements of the arraylist in the hashMap to count the frequency.

This is exactly the same thing that tweakt says with a code sample. – mP. Feb 3 '09 at 4:25.

Counting the occurrences of all items in a list is also known as "tallying" a list, or creating a tally counter. (or similarly with a dictionary dict((x,l. How much faster is Counter?

I checked how much faster Counter is for tallying lists. I tried both methods out with a few values of n and it appears that Counter is faster by a constant factor of approximately 2.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions