2016-11-15 28 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”的要求。