1
\$\begingroup\$

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;
            }
        }
    };
}
\$\endgroup\$
3
  • \$\begingroup\$ Entry(String) and Entry.toString seems irrelevant for the question. \$\endgroup\$ Oct 21, 2017 at 23:47
  • 2
    \$\begingroup\$ Comparator.comparingLong(Entry::getCount) would be the shorter equivalent in Java 8+. \$\endgroup\$
    – 4castle
    Oct 22, 2017 at 2:10
  • \$\begingroup\$ @4castle you can post that as an answer (and you should get at least as many points as me). Otherwise I'll take it over in my answer. \$\endgroup\$ Oct 22, 2017 at 13:58

1 Answer 1

2
\$\begingroup\$

The comparator should work fine, however return Integer.compare(int, int) avoid the re-invention of the wheel.

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.