-1

If I have a text file with the following appearance:
john1337 score: 80
may10 score: 23
dfawfawf score: 40
heyhey score: 100
flow32 score: 25

How do I read only the top 3 scores in order and display them?
So it would be:
heyhey score: 100
john1337 score: 80
dfawfawf score: 40

Im trying to avoid sorting the integers by the names i.e 'john1337' and instead displaying the actual score-line in order, how do I do this?

substess
  • 7
  • 2

2 Answers2

1

There is a stream solution just for educational purposes, but you probably should try to implement it classical way.

Comparator<String> comparator = Comparator.comparing(o -> Integer.valueOf(o.split(":")[1].trim()));
Comparator<String> reversed = comparator.reversed();

Files.lines(Paths.get(PATH_TO_FILE))
        .sorted(reversed)
        .limit(3)
        .forEach(System.out::println);

Here the Comparator is used to sort all lines by score. Then using limit the stream is truncated to be no longer than 3.

Ruslan
  • 6,090
  • 1
  • 21
  • 36
0

You can't access the 3 top scores without knowing, where they are located in the file. So you need to know where the top scores are located in the file. For this, you need to read all scores from the file, parse the strings (eg. split at ":", remove the word " score" and trim the resulting strings), and evaluate the scores. You can sort them using a hashmap or similar. So, your idea is not possible using a simple text file as datasource. If you would use a database for example you could create a query, which returns the top 3 scores.

Marvin Klar
  • 1,869
  • 3
  • 14
  • 32