-5

Ive got a file called HighScores.txt which contains player names and number of points:

name1 2
name2 5
name3 1
name4 23
name5 51

And heres my code that reads the contents of this file, splitting each line and appending it to the ArrayList highScores:

public class fileHandling {

    static ArrayList highScores = new ArrayList();


    public static void readFile(String[] args) throws Exception {

        File file = new File(fileHandling.class.getClassLoader()
                .getResource("HighScores.txt").getPath());

        Scanner read = new Scanner(file);

        while (read.hasNextLine()) {
            String line = read.nextLine();
            String[] result = line.split("\\s+");
            highScores.add(Arrays.toString(result));
            System.out.println(highScores);

        }
    }

}

How do i then sort this ArrayList by the number of points each player has?

i.e. so the new array list will be:

[[name5, 51], [name4, 23], [name2, 5], [name1, 2], [name3, 1]]
Oliver Bennett
  • 157
  • 1
  • 2
  • 14

2 Answers2

3

You can create a separate object for every line in your file and then use Comparable or Comparator interface to sort these objects. Then use Collections.sort(arrayList,sorter). You can find a good tutorial here to sort user defined objects.

The class for the same can be

public class Player{
     private String name;
     private Integer score;

     //getters and setters here
}

Then create a sorter for Player objects as follows.

public class ScoreSort implements Comparator<Player>{
    public int compareTo(Player first, Player second){
            // implement sorting logic here

    }
}

Then use Collections.sort(playerList, new ScoreSort()). You can find a good tutorial at following link

http://www.thejavageek.com/2013/06/17/sorting-user-defined-objects-part-2/

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
2

Create a class with 2 member variable name and score. Create a new instance of class for each entry in file and store it in ArrayList. Now this class should also implement Comparable interface which compares based on score. Now use Collections.sort

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
Lokesh
  • 7,810
  • 6
  • 48
  • 78