How to sort an array of objects in java

Asked

Viewed 960 times

1

Hello, I have a class teams where they have scores (int), winning number (int), defeats (int) etc. Within the method main, 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 need to print it on the screen. If anyone can help I’d be grateful.

  • Eduardo, welcome to Sopt. Go to Ajuda and take the Tour. For your question to be properly answered here, you need to post part of your code. The community helps, but it doesn’t do for us what we need. There are numerous and different possibilities of solving these broad questions, there needs to be "where to start" to be able to help you with a problem or difficulty.

1 answer

2


Try to use the method Arrays.sort(T[], Comparator<? super T>) thus:

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 a NullPointerException.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.