JorD
JorD

Reputation: 11

Sorting an ArrayList by the second word in a string

I've currently got a .txt file i need to read and output data based on what is inside. I've currently got the file to open and saved each line in the file into an ArrayList.

The .txt file is setup like this ;

Current code ;

 {
    try {
        File file = new File("input.txt");
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        StringBuffer stringBuffer = new StringBuffer();
        String line;
        ArrayList<String> txtline = new ArrayList<String>();
        while ((line = bufferedReader.readLine()) != null) {
            txtline.add(line);
            System.out.println(txtline);
        }

        fileReader.close();
        System.out.println(stringBuffer.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

I'm just wondering if there is a way to sort each line of text by the 2nd large number, I've looked and I just can't seem to find anything. A point in the right direction or some guidance would be amazing as I'm currently stumped as I need to do this before i progress any further.

Upvotes: 1

Views: 1699

Answers (2)

Ousmane D.
Ousmane D.

Reputation: 56433

You can accomplish the task at hand by creating a stream of the list, passing in a Comparator object to the sorted method to define the sort key and then collect it into an ArrayList.

comparing numerically:

txtline = txtline.stream()
                 .sorted(Comparator.comparingLong((String e) -> Long.parseLong(e.split(" ")[1])))                             
                 .collect(Collectors.toCollection(ArrayList::new));

comparing by strings:

txtline = txtline.stream()
                 .sorted(Comparator.comparing((String e) -> e.split(" ")[1]))
                 .collect(Collectors.toCollection(ArrayList::new));

Upvotes: 2

Leo Aso
Leo Aso

Reputation: 12463

Put this after your while-loop

java.util.Collections.sort(txtLine, new Comparator<String>() {
    public void compare(String lineA, String lineB) {
        String wordA2 = lineA.split(" ")[1];
        String wordB2 = lineB.split(" ")[1];
        return wordA2.compareTo(wordB2);
    }
});

Can be done more efficiently, but the code doesn't get much shorter than this (unless you use lambdas).

java.util.Collections.sort(txtLine, (String lineA, String lineB) -> {
        String wordA2 = lineA.split(" ")[1];
        String wordB2 = lineB.split(" ")[1];
        return wordA2.compareTo(wordB2);
});

Upvotes: 1

Related Questions