我的程序必須使用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);
}
}
}
}
你想讓它們按數字或字典順序排序嗎?但也許你可以將它們存儲在地圖中。 – bradimus
Lexicograpically –
使用從字符串到整數的映射,然後對鍵進行排序並按排序順序提取值? –