Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a List<String> according to the length of the strings and print the first N elements

Your program should read an input file (the first argument to your program). The first line contains the value of the number 'N' followed by multiple lines. You may assume that the input file is formatted correctly and the number on the first line i.e. 'N' is a valid positive integer.e.g.

This is my Input:

2
Hello World

CodeEval
Quick Fox
A
San Francisco

Desired Output should be:

San Francisco
Hello World

This is my code:

 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));
    }

}   

}

But i am getting this output:

San Francisco
Quick Fox

Where am i going wrong?

like image 263
AB25 Avatar asked Dec 13 '25 21:12

AB25


1 Answers

Tje default sorting, will sort the list according to the alphabetical index. If you want to sort for other criterias, like the length in your case, you must implement oyur own 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);
like image 80
Devolus Avatar answered Dec 15 '25 12:12

Devolus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!