集合排序以对两个ArrayList进行相同排序

Ale*_*ngs 3 java sorting collections arraylist

我的程序必须使用Collections排序方法按字典顺序对字符串的ArrayList进行排序,但是每个字符串都有一个对应的整数值,该值存储在单独的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);
            }
        }
    }    
}
Run Code Online (Sandbox Code Playgroud)

Gho*_*ica 5

您弄错了抽象。如果该字符串和该数字属于同一类,则不要将它们放在两个不同的列表中。

而是创建一个保存这两个值的类(或使用现有的Pair类之一)。然后,您可以为该类提供一个equals方法。加上一个特定的比较器,该比较仅比较字符串元素。

最后,将该类的对象放入单个列表中。然后你解决名单。

好的OO编程的全部思想是创建有用的抽象

记录一下:正如dnault所建议的那样,如果字符串和数字之间确实没有“紧密”的耦合,则还可以使用TreeMap(用作TreeMap<String, Integer>)来对带有数字的字符串进行排序。

  • TreeMap &lt;String,Integer&gt;也可能是可行的选择。 (2认同)