Gherbi Hicham Gherbi Hicham - 5 months ago 14
Java Question

Data Structure to sort elements by values

I need a data structure in Java that can manipulate

String
s, compute the frequency of each word in an
ArrayList<String>
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
HashMap
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
String
and its occurence instead of a list for the
String
s and annother for the frequency).

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

Answer

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> {
        @Override
            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