2017-01-23 18 views
0

我有一個程序需要一個單詞和一個文本文件字典,並搜索字典中與給定單詞相等(都是anagrams)的單詞組合。字符串數組的排列Array列表Java

我最終得到了一個String數組的Arraylist,每個數組都是一個包含它使用的單詞的解決方案,而Arraylist是所有的解決方案。

我然後遍歷數組列表和數組作爲排序:

List<String> list = Arrays.asList(array); 
list.sort(Comparator.comparing(String::length).reversed().thenComparing(String::compareTo)); 

,其通過字長度(降序)排序第一,然後使用字母作爲仲裁斷路器相等的長度的話。

我現在已經單獨的陣列進行排序,但我試圖將它們按照一定的規則在ArrayList中的排序:按升序話

  • 的數量包含單詞的數量相等陣列

    • ,和所有單詞長度相同,數組按字母順序排序。
    • 字數相等,但長度不同:最長不等長的第一個。例如,如果[0]長度== b [0]長度但b [1]長度> a [1]長度,則b首先出現。

    它們已經按單詞升序存儲,因爲單詞解決方案首先被發現,然後是2個單詞等,被附加到數組列表中。

    現在,隨着排序後,數組也是在降序字長的順序,我認爲必須有一個簡單的比較器來實現上述,但我努力做到這一點。

  • 回答

    0

    首先,沒有必要將數組轉換爲List以進行排序。

    其次,你應該使用thenComparing(Comparator.naturalOrder()),而不是thenComparing(String::compareTo),因爲它將使用Comparator,而不是創建一個新的Comparator委託給方法的參考。

    至於你的問題,我不認爲那裏存在Comparator,所以只需創建你自己的。使用thenComparing()建設化合物Comparator很好,但並不總是正確的路。

    所以,你的代碼可能是(假設我有你的排序條件右)

    List<String[]> solutions = /* code here */; 
    
    // First, sort each individual solution (array) 
    for (String[] solution : solutions) { 
        Arrays.sort(solution, Comparator.comparing(String::length) 
                .reversed() 
                .thenComparing(Comparator.naturalOrder())); 
    } 
    
    // Second, sort the solutions (list) 
    solutions.sort((solution1, solution2) -> { 
         // 1) By number of words (ascending) 
         int cmp = Integer.compare(solution1.length, solution2.length); 
         // 2) By length of word (descending) 
         for (int i = 0; cmp == 0 && i < solution1.length; i++) 
          cmp = Integer.compare(solution2[i].length(), solution1[i].length()); 
         // 3) Alphabetically (ascending) 
         for (int i = 0; cmp == 0 && i < solution1.length; i++) 
          cmp = solution1[i].compareTo(solution2[i]); 
         return cmp; 
    });