2

Right now I have something in php that looks like this:

$count = array_count_values($result);
arsort($count);

foreach($count as $key => $val){
    $result[] = $key;
}

It will count all the items in the array and put it into a key/value pair. Which will remove the duplicates and then I tell it to sort. Then I take the key of it and store it. Is there a way to do this in Java?

1
  • I don't think your code is doing what you think it's doing. arsort doesn't sort by the value in the array. It sorts by the key. Commented Aug 27, 2012 at 21:07

2 Answers 2

2

I don't believe Java has an equivalent to the array_count_values function, so you will need to implement that yourself. Something like this:

public static <T> Map<T, Integer> countValues(List<T> values) {
    Map<T, Integer> result = new HashMap<T, Integer>();
    // iterate through values, and increment its corresponding value in result
    return result;
}

Then use the java.util.Collections.sort(List list, Comparator c) function to sort the array by the counts. You'll need to implement Comparator to sort by the counts.

public class CountComparator<T> implements Comparator<T> {
    private Map<T, Integer> counts;

    public CountComparator(Map<T, Integer> counts) {
        this.counts = counts;
    }

    public int compare(T o1, T o2) {
        // assumes that the map contains all keys
        return counts.get(o1).compareTo(counts.get(o2));
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

How about using a Multiset from the Google Guava library to get counts. It works in a similar way to PHP's array_count_values.

If you want it sorted by the key, then use the TreeMultiset implementation.

If you want it sorted on count, then use Multisets.copyHighestCountFirst

1 Comment

If you want it sorted by count, then that blog post is out of date.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.