I have the following code in Java:
public class ServerInfo {
int serverId;
int serverDataRate;
public ServerInfo(int serverId, int serverDataRate) {
this.serverId = serverId;
this.serverDataRate = serverDataRate;
}
public int getServerId() {
return serverId;
}
public double getServerDataRate() {
return serverDataRate;
}
public String toString(){
return serverId + ":" + serverDataRate;
}
}
public class ServerInfoComparator implements Comparator<ServerInfo> {
@Override
public int compare(ServerInfo o1, ServerInfo o2) {
double datarate1=o1.getServerDataRate();
double datarate2=o2.getServerDataRate();
if(datarate1>datarate2)
return -1;
else if(datarate1<datarate2)
return +1;
else
return 0;
}
}
public class Sample {
List<ServerInfo> listOfServers= new ArrayList<ServerInfo>();
public void insertIntoList(){
listOfServers.add( new ServerInfo(0,256));
listOfServers.add( new ServerInfo(1,270));
listOfServers.add( new ServerInfo(2,256));
listOfServers.add( new ServerInfo(3,290));
listOfServers.add( new ServerInfo(4,300));
listOfServers.add( new ServerInfo(5,300));
listOfServers.add( new ServerInfo(6,256));
listOfServers.add( new ServerInfo(7,265));
listOfServers.add( new ServerInfo(8,289));
listOfServers.add( new ServerInfo(9,310));
}
public static void main( String[] args){
Sample s = new Sample();
s.insertIntoList();
ServerInfoComparator com = new ServerInfoComparator();
Collections.sort(s.listOfServers,com);
for( ServerInfo server: s.listOfServers){
System.out.println(server);
}
}
}
I am using the above code to sort the elements in descending order based on the serverDataRate. Here the sample set is quite small supposing I have a larger sample set of 100 elements in the list and the code had to be executed every 5-10 seconds. Is this the fastest way to sort the list or is there a faster method I am not aware of?
I changed your test
and it prints
That’s quite a bit faster 😉
BTW: I changed the
doublefields to beint.