Gherbi Hicham Gherbi Hicham - 1 year ago 44
Java Question

Data Structure to sort elements by values

I need a data structure in Java that can manipulate

s, compute the frequency of each word in an
and then I need to sort them based on the frequencies.

To put it simply, the data structure needs to be an associative array, that can be sorted BY VALUES , I already put the lines into the
and got surprised by the fact that it can't be sorted , now I'm stuck thinking about another data structure.

P.S. (using two lists is not suited to my program because it needs to do a lot of calculations, so it would be better if a single structure holds each
and its occurence instead of a list for the
s and annother for the frequency).

EDIT: I appreciate the help, but some people are suggesting a
, so I want to specify something here: I need the structure sorted by the occurences of the strings (in the case of
s it would be the values not the keys).


I don't think there is a simple data structure for this.

First, the frequency is going to be changing when you are collecting the frequency data. For which the sorting should comes after the all string frequency is collected.

The easiest way I can think of is:

// psuedo-code
final Map<String, Integer> stringFreq = ....; // it doesn't matter what kind of impl you use

// collect the String vs frequency in stringFreq

Map<String, Integer> result = new TreeMap<String, Integer>(stringFreq, 
        new Comparator<String> {
            public int compare(String a, String b) {
                int aFreq = stringFreq.get(a);
                int bFreq = stringFreq.get(b);
                return (a==b)?a.compareTo(b) : (a-b);

// result should have data sorted by frequency, and then the string value