Dragonfly
Dragonfly

Reputation: 4361

Sort arraylist by number of times in arraylist and then remove duplicates

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?

Upvotes: 2

Views: 801

Answers (2)

theon
theon

Reputation: 14420

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

Upvotes: 0

Brigham
Brigham

Reputation: 14564

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

Upvotes: 2

Related Questions