2016-08-02 37 views
-1

我需要幫助。用兩個不同的值對HashSet進行排序?

我有一個類型爲<的HashSet ResultEmployee>。

ResultEmployee包含Employee(包含id,名稱,電子郵件等)和兩個名爲「halfHits」和「fullHits」的成員。我遍歷一組員工來查找包含.equals或.contains字符串的字符串。 「halfHits」和「fullHits」成員對此結果進行計數。

我的輸出:

米亞史密斯,0 FullHits,1個HalfHits

MAIK月,3個FullHits,2個HalfHits

前夕您好,2個FullHits,0 HalfHits

蒂娜特洛伊3 FullHits,1 HalfHits

等等......

示例輸出,我想:

MAIK月,3個FullHits,2個HalfHits

蒂娜特洛伊,3個FullHits,1個HalfHits

前夕您好,2個FullHits,0 HalfHits

米亞史密斯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出來。

+0

如果你表現出類的代碼,而不是描述它們,這將是更清晰。另請參閱如何創建[mcve]。 – assylias

+1

和特製你可比做了嘗試,看你做錯了 – dquijada

+2

考慮使用[TreeSet中有一個自定義的比較(https://docs.oracle.com/javase/8/docs/api/java/util/什麼TreeSet.html#TreeSet-java.util.Comparator-) – bradimus

回答

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))); 
+0

哦,我的天哪,非常感謝你......這對我有用:) –

相關問題