按两个不同的值对HashSet进行排序?

时间:2016-08-02 14:09:19

标签: java sorting hashset comparable

我需要帮助。

我有一个类型为<的HashSet ResultEmployee>。

ResultEmployee包含Employee(包含id,name,email等)和两个名为“halfHits”和“fullHits”的成员。我遍历一组员工,找到.equals或.contains字符串我搜索的字符串。 “halfHits”和“fullHits”成员统计此结果。

我的输出:

Mia Smith,0 FullHits,1 HalfHits

Maik May,3 FullHits,2 HalfHits

Eve你好,2个FullHits,0个HalfHits

Tina Troy,3个FullHits,1个HalfHits

依旧......

我想要的输出示例:

Maik May,3 FullHits,2 HalfHits

Tina Troy,3个FullHits,1个HalfHits

Eve你好,2个FullHits,0个HalfHits

Mia Smith,0 FullHits,1 HalfHits

依旧......

问题: 我不知道如何用两个不同的值对HashSet进行排序。 我试过Comparable,但是我失败了。我不知道该怎么做 像这样。请帮我。我不知道,我怎么能接近这样的事情。我试过这样的事情:

 public class SortHelper implements Comparator<ResultEmployee> {

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

但这只是比较fullHits并将halfHits抛出。

1 个答案:

答案 0 :(得分:1)

不确定为什么你有投射,我猜测ResultEmployee的实现,但尝试

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.
    }
}

然后

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

当您插入时,该组将被分类。

在Java 8中,您可以使用

而不是定义SortHelper
 Set<ResultEmployee> set = new TreeSet<>(Comparator.comparing(ResultEmployee::getFullHits).thenComparing(Comparator.comparing(ResultEmployee::getHalfHits)));