按两个不同的值对 HashSet 进行排序?
Sort an HashSet by two different values?
我需要帮助。
我有一个类型为 的 HashSet。
ResultEmployee 包含 Employee(包含 id、name、email 等)和两个名为 "halfHits" 和 "fullHits" 的成员。我遍历一组员工以查找 .equals 或 .contains 我搜索的字符串的字符串。 "halfHits" 和 "fullHits" 成员计算此结果。
我的输出:
米娅·史密斯,0 次全命中,1 次半命中
Maik May,3 次 FullHits,2 次 HalfHits
Eve Hello,2 个 FullHits,0 个 HalfHits
蒂娜·特洛伊,3 次全命中,1 次半命中
等等...
我想要的示例输出:
Maik May,3 次 FullHits,2 次 HalfHits
蒂娜·特洛伊,3 次全命中,1 次半命中
Eve Hello,2 个 FullHits,0 个 HalfHits
米娅·史密斯,0 次全命中,1 次半命中
等等...
问题:
我不知道如何按两个不同的值对 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。
不确定为什么要进行转换,我猜测 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)));
我需要帮助。
我有一个类型为
ResultEmployee 包含 Employee(包含 id、name、email 等)和两个名为 "halfHits" 和 "fullHits" 的成员。我遍历一组员工以查找 .equals 或 .contains 我搜索的字符串的字符串。 "halfHits" 和 "fullHits" 成员计算此结果。
我的输出:
米娅·史密斯,0 次全命中,1 次半命中
Maik May,3 次 FullHits,2 次 HalfHits
Eve Hello,2 个 FullHits,0 个 HalfHits
蒂娜·特洛伊,3 次全命中,1 次半命中
等等...
我想要的示例输出:
Maik May,3 次 FullHits,2 次 HalfHits
蒂娜·特洛伊,3 次全命中,1 次半命中
Eve Hello,2 个 FullHits,0 个 HalfHits
米娅·史密斯,0 次全命中,1 次半命中
等等...
问题: 我不知道如何按两个不同的值对 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。
不确定为什么要进行转换,我猜测 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)));