How to sort an array of objects in java

1
Hello, I have a class times where they have score (% with%), number of wins (% with%), losses (% with%), etc. Within the int method, I have an array of 20 teams and need to sort them by the score, if the score is equal, I check who has the most wins and I need to print this on the screen. If anyone can help, I'll be grateful.

    
asked by anonymous 15.07.2016 / 06:12

1 answer

2

Try using the Arrays.sort(T[], Comparator<? super T>) like this:

Time[] times = ...;
Arrays.sort(times, (a, b) -> {
   int pa = a.getPontos();
   int pb = b.getPontos();
   return pa == pb ? a.getVitorias() - b.getVitorias() : pa - pb;
});

Just make sure before there is no element null in the array, or else this code will give NullPointerException .

At the end, to print the names, after sorting, simply use a for simple and print the names of the teams one by one.

    
15.07.2016 / 06:37