Search code examples
javasortingfile-iolinked-listcomparable

reading lines in from a text file and sorting them into a linked list java


I need to read in each line from a text file, and sort it according to length first, and then it's position in the original document, before adding the lines to a linked list.

The contents of the list must then be printed out, line by line, with a prefix indicating which line number is being printed out, and how many non-space characters are on the line.

Below is a sample I/O:

Input (i.e. contents of text file)

this
is
just
a
test

Output

1/1: a
2/2: is
3/4: this
4/4: just
5/4: test

Solution

    1. I need to read in each line from a text file : Use FileReader and BufferedReader
    2. and sort it according to length first, and then it's position in the original document, before adding the lines to a linked list : create a HashMap with (String,lineNo) of original doc.
    3. Use Comparator to sort - first by length, then by line pos (get it from hashMap)using ternary operator .

    4. how many non-space characters are on the line : split the line using "s+" . add the lengths of all the sub arrays using a for loop.

    5. while printing from the arraylist, print count + nonSpaceChars in line + line .

    Hope this will be sufficient