我的程序必须使用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 –
使用从字符串到整数的映射,然后对键进行排序并按排序顺序提取值? –