Problem
I am trying to compare Entries by their frequencies using Comparator. I wanna know if this piece of code would work for this case?
// Creates entries
private class Entry {
private String word;
private long count;
public Entry(String w, long c) {
word = w;
count = c;
}
public String getWord() { return word; }
public long getCount() { return count; }
public Entry(String entry) {
String parts[] = entry.split("t");
word = parts[1].trim();
count = new Long(parts[0].trim());
}
public String toString() {
return "(" + word + "," + count + ")";
}
}
// compare Entry objects by their frequencies
private static Comparator<Entry> countComparator() {
return new Comparator<Entry>() {
public int compare(Entry e1, Entry e2) {
if(e1.getCount() > e2.getCount()) {
return 1;
}
else if(e1.getCount() < e2.getCount()) {
return -1;
}
else {
return 0;
}
}
};
}
Solution
The comparator should work fine, however return Integer.compare(int, int)
avoid the re-invention of the wheel.