2016-11-15 29 views
1

我的程序必須使用Collections排序方法按字典順序排列字符串的ArrayList,但每個String都有一個對應的整數值存儲在單獨的ArrayList中。我想對它們進行排序,因此整數值保留在正確的字符串中。如果你知道一個更好的方式來存儲這兩個值,我就會全神貫注。Collections排序將兩個ArrayList排序相同

public class a5p1b { 
    public static void main(String[] args) { 

     Scanner input = new Scanner(System.in).useDelimiter("[^a-zA-z]+"); 
     // ArrayLists to store the Strings and the frequencies 
     ArrayList<String> lst = new ArrayList<String>(); 
     ArrayList<Integer> intLst = new ArrayList<Integer>(); 

     //loops through as long as there is user input 
     while (input.hasNext()) { 
      String str = input.next().toLowerCase(); 
      // if the list already has the string it doesn't add it and it 
      // ups the count by 1 
      if (lst.contains(str)) { 
       int index = lst.indexOf(str); 
       intLst.set(index, intLst.get(index) + 1); 
      } else { 
       // if the word hasnt been found yet it adds it to the list 
       lst.add(str); 
       intLst.add(1); 
      } 
     } 
    }  
} 
+0

你想讓它們按數字或字典順序排序嗎?但也許你可以將它們存儲在地圖中。 – bradimus

+0

Lexicograpically –

+0

使用從字符串到整數的映射,然後對鍵進行排序並按排序順序提取值? –

回答

4

您正在使您的抽象錯誤。如果該字符串和該號碼屬於一起,則執行而不是將它們保留在兩個不同列表中。

取而代之的是創建一個類(或者可以使用現有的Pair類之一)來保存這兩個值。然後,您可以爲該類提供一個equals方法;加上一個特定的comparator,它只比較字符串元素。

最後,您將該類的對象放入一個單個的列表中;然後你排序列表。

良好的面向對象編程的整個想法是創建有用的抽象

爲了記錄:作爲dnault建議,如果真有字符串和數字之間沒有任何「從緊」的耦合,你也可以使用一個TreeMap(用作TreeMap<String, Integer>)採取的是有一些與他們字符串進行排序的護理。

+2

TreeMap 也可能是一個可行的選擇。 – dnault

+0

@dnault我在走狗時有同樣的想法;但感謝您的意見;我相應地更新了我的答案。 – GhostCat

0

嘗試

inList.sort(Comparator.comparing(i -> i.toString()); 

雖然,我不認爲這兩個列表是一個好主意。

0

您應該使用Map將每個唯一的String鍵與一個Integer值相關聯。

然後,您可以調用keySet()返回的地圖的一組密鑰上的Collections.sort。

此外,如果您使用SortedMap(如TreeMap),則不需要對鍵進行排序。但是,該解決方案可能無法滿足「作業5問題1b」的要求。