Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

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

share|improve this question
1  
Do you see still same order or they are not sorted as per expected order ? – Sachin Thapa Sep 24 '13 at 15:05
    
Does it sort your objects according to bandwidth in reverse order then? – dasblinkenlight Sep 24 '13 at 15:05
    
I see the same order – Umair Iqbal Sep 24 '13 at 15:06
    
It looks good actually :/ The only change I would make is changing the compare method to: return s2.getBandwidth() - s1.getBandwidth(); – Marcelo Sep 24 '13 at 15:07
1  
The one-line version of your function - return -Integer.compare(s1.getBandwidth(), s2.getBandwidth()) – Dukeling Sep 24 '13 at 15:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.