I have a HashMap which I copy to an ArrayList and then I want to sort the entries in my List according to the bandwidth of each entry, the higher the bandwidth the first it should come in my list Here is what I tried
Main Class
ArrayList<Signal> messages = new ArrayList<Signal>();
messages.addAll(map.values());
Collections.sort(messages, new MyComparator());
My Comparator Class
public class MyComparator implements Comparator<Signal>{
@Override
public int compare(Signal s1, Signal s2) {
if (s1.getBandwidth() > s2.getBandwidth() ) {
return -1;
} else if (s1.getBandwidth() < s2.getBandwidth()) {
return 1;
}
return 0;
}
}
It does not sort my signal objects according to bandwidth ?
What I am doing wrong
Problem Solved
Actually I was not setting the bandwidth before sorting it
Here is the code Hope it will help some one
public void createSortedSet(HashMap<String, Signal> map,
final BufferedWriter buffwriter, long totalSize) {
try {
messages.addAll(map.values());
for (Signal signal : messages) {
signal.setBandwidth((signal.getSize() / (float) totalSize) * 100);
}
Collections.sort(messages, new MyComparator());
} catch (Exception e) {
e.printStackTrace();
}
createCSV(buffwriter, messages);
}
Thanks
return s2.getBandwidth() - s1.getBandwidth();
– Marcelo Sep 24 '13 at 15:07return -Integer.compare(s1.getBandwidth(), s2.getBandwidth())
– Dukeling Sep 24 '13 at 15:11