如何根据字符串的长度对List <string>进行排序并打印前N个元素</string>

时间:2013-06-29 08:26:11

标签: java string arraylist

您的程序应该读取输入文件(程序的第一个参数)。第一行包含数字'N'的值,后跟多行。您可以假设输入文件格式正确,第一行的数字即'N'是有效的正整数。

这是我的输入:

  

2
  Hello World

     

CodeEval
  快狐   一个
  旧金山

期望的输出应该是:

  

旧金山
  Hello World

这是我的代码:

 class Longest
 {
public static void main(String args[]) throws FileNotFoundException  
{
    BufferedReader in = null;
    List<String> myList = new ArrayList<String>();
    try 
    {   
        in = new BufferedReader(new FileReader("C:\\filename.txt"));
        String str;
        while ((str = in.readLine()) != null) 
        {
            if (str.length() == 0) continue;                                

            myList.add(str);
        }
    } 
    catch (IOException e) 
    {
        e.printStackTrace();
    } 
    System.out.println("Contents of the ArrayList : "+myList);
    System.out.println("Size of the ArrayList : "+myList.size());
    String s = myList.remove(0);
    System.out.println(System.getProperty("line.separator"));
    System.out.println("Number of lines to be printed : "+s);
    System.out.println("After removing first element of ArrayList : "+myList);
    System.out.println("Size of the ArrayList : "+myList.size());               

    Comparator comparator=Collections.reverseOrder();                   
    Collections.sort(myList,comparator);
    System.out.println("After sorting ArrayList in Descending Order :"+myList);


    int x = Integer.parseInt(s);
    System.out.println(System.getProperty("line.separator"));


for (String s1 : myList) {
System.out.println(s1);
}
System.out.println(System.getProperty("line.separator"));

for(int i=0; i<x; i++){
        System.out.println(myList.get(i));
    }

}   

}

但是我得到了这个输出:

  

旧金山
  快狐狸

我哪里错了?

2 个答案:

答案 0 :(得分:11)

默认排序将根据字母索引对列表进行排序。如果您想要对其他标准进行排序,例如您的案例中的长度,则必须实现自己的Comparator

    Comparator<String> x = new Comparator<String>()
    {
        @Override
        public int compare(String o1, String o2)
        {
            if(o1.length() > o2.length())
                return -1;

            if(o2.length() > o1.length())
                return 1;

            return 0;
        }
    };

    Collections.sort(mylist,  x);

答案 1 :(得分:0)

在您的代码中,您只需删除列表中的第一项(myList)。 然后列表的大小为4。 然后你以相反的顺序排列列表,这是正常的,你得到输出:

San Francisco
Quick Fox
Hello World
CodeEval
A

据我所知,您刚删除了第一个元素,因此您的输出将包含5个元素。我不明白为什么你想得到所需的输出。输出按字母顺序反转。

相关问题