Ben
Ben

Reputation: 391

Count number of occurences of an element in an array

I have an ArrayList<ArrayList<String>> and I want to count the number of times an element shows up in the list. I also need it with respect to the 3rd element too.

[Demo-Site, "", blah1, 09:58:59, 2015-08-19]
[hitta, "", blah4, 11:17:14, 2015-08-19]
[Demo-Site, "", blah1, 11:26:30, 2015-08-19]
[poc-wim, "", blah2, 11:26:54, 2015-08-19]
[poc-wim, "", blah3, 11:29:46, 2015-08-19]

Output should be:

[Demo-Site, 2, blah1, 2015-08-19]
[Hitta, 1, blah4, 2015-08-19]
[poc-wim, 1, blah2, 2015-08-19]
[poc-wim, 1, blah3, 2015-08-19]

I know I can do this for an array list, but not too sure how to do it with respect the the third element?

private static void rawReport(ArrayList<ArrayList<String>> data) {
    Map<String, Integer> counts = new HashMap<String, Integer>();

    for(ArrayList<String> key: data) {
        Integer count = counts.get(key.get(0));
        if (count == null) {
            count = 0;
        }
        count++;
        counts.put(key.get(0), count);
    }

    for (Entry<String, Integer> entry : counts) {
        System.out.println(entry.getKey() + " " + entry.getValue());
    }
}

Upvotes: 0

Views: 174

Answers (1)

Damon Horrell
Damon Horrell

Reputation: 2264

You can use a map for this.

Declare it with:

Map<String, Integer> counts = new HashMap<String, Integer>;

and then iterate over your data and use the following to add each key:

Integer count = counts.get(key);
if (count == null) {
  count = 0;
}
count++;
counts.put(key, count);

Then you can print out the counts with:

for (Entry<String, Integer> entry : counts.entrySet()) {
  System.out.println(entry.getKey() + " " + entry.getValue());
}

If you have a multi-part key (1st, 3rd, and possibly 5th column) then you could either concatenate them together to form the key as a string, or alternatively use Map<Key, Integer> instead where Key is a class you create to represent the key which will need to have hashCode and equals methods defined.

Or if you're using Java 8 then it now has some built-in stuff to do this but it's a good idea to understand how to do it yourself first.

Damon

Upvotes: 1

Related Questions