Reputation: 2499
I have two arrays, one is String[] and other is int[]. The values in the integer array correspond to the elements of the String array. For example, the String array contains the names of some teams and another int array contains their points in the league. I can sort the int array using Arrays.sort and I want to sort the String array according to the points and if two teams have same points, I should arrange them alphabetically.
I thing I can make a 2D array but how to sort it then?
Upvotes: 2
Views: 1394
Reputation: 955
Create a class and add two comparators:
class Team{
private String teamName;
private int leaguePoints;
public static final Comparator<Team> BY_NAME = new ByName();
public static final Comparator<Team> BY_POINTS = new ByPoints();
private static class ByName implements Comparator<Team>
{
public int compare(Team a, Team b)
return a.name.compareTo(b.name);
}
private static class ByPoints implements Comparator<Team>
{
public int compare(Team a, Team b)
return a.leaguePoints - b.leaguePoints;
}
}
Then sort the array for this class, using the BY_NAME
comparator first and then by BY_POINTS
.
Arrays.sort(array, Team.BY_NAME);
Arrays.sort(array, Team.BY_POINTS);
Make sure to use stable sort to preserve the relative order of equal keys (That is if points are equal, then unstable sort like selection sort might mess up the sorted order of team names).
Upvotes: 0
Reputation: 38531
Consider creating a class:
class Team {
String name;
int numPoints;
}
and having an array Team[] teams
. You can then create a comparator for these objects that sort based on both String
and Integer
criteria.
Upvotes: 4
Reputation: 2812
You'd have an easy time doing that if you created a class that contains both values for a team, and have the class implement Comparable interface. Then it would be trivial to sort an array of these objects using Arrays.sort.
Upvotes: 1