Franziska Gerlich Franziska Gerlich - 4 months ago 16
Java Question

Sort an HashSet by two different values?

I need help.

I have an HashSet with type < ResultEmployee >.

ResultEmployee contains Employee(which contains id, name, email and so on) and two member named "halfHits" and "fullHits". I iterate over a Set of employees to find Strings that .equals or .contains a string I search for. The "halfHits" and "fullHits" member Count this results.

My Output:

Mia Smith, 0 FullHits, 1 HalfHits

Maik May, 3 FullHits, 2 HalfHits

Eve Hello, 2 FullHits, 0 HalfHits

Tina Troy, 3 FullHits, 1 HalfHits

and so on...

Example Output that I want:

Maik May, 3 FullHits, 2 HalfHits

Tina Troy, 3 FullHits, 1 HalfHits

Eve Hello, 2 FullHits, 0 HalfHits

Mia Smith, 0 FullHits, 1 HalfHits

and so on...

Problem:
I don't know how to sort a HashSet by two different values.
I tried with Comparable, but I failed. I don't know how to do something
like this. Please help me. I have no idea, how can I approach something like this. I tried something like this:

public class SortHelper implements Comparator<ResultEmployee> {

@Override
public int compare(ResultEmployee o1, ResultEmployee o2) {
return ((Integer)o1.getFullHits()).compareTo((Integer)o2.getFullHits());
}
}


But this only compares the fullHits and leave halfHits out.

Answer

Not sure why you have the casting and I'm guessing at the implementation of ResultEmployee, but try

public class SortHelper implements Comparator<ResultEmployee> {

    @Override
    public int compare(ResultEmployee o1, ResultEmployee o2) {
        int result =((Integer)o1.getFullHits()).compareTo((Integer)o2.getFullHits());
        if (result == 0) { // Full hits were the same
            result = ((Integer)o1.getHalfHits()).compareTo((Integer)o2.getHalfHits());
        }
        return result.
    }
}

Then

Set<ResultEmployee> set = new TreeSet<>(new SortHelper());

The set will be sorted as you insert.

In Java 8, instead of defining SortHelper you can use

 Set<ResultEmployee> set = new TreeSet<>(Comparator.comparing(ResultEmployee::getFullHits).thenComparing(Comparator.comparing(ResultEmployee::getHalfHits)));
Comments