1
import java.util.*;

public class CW3 {

 private static HashMap < String, Integer > map = new HashMap < String, Integer > ();

 int comp(String s1, String s2) {
    int i1 = map.get(s1);
    int i2 = map.get(s2);
    if (i1 < i2)
    return -1 ;
    else if (i1 == i2)
    return 0;
    else 
    return 1;
}

 void sort(List l) {
     Comparator c = new Comparator() {
      public int compare(Object o1,Object o2) {   
          String a = (String)o1;
          String b = (String)o2;
          int result = new CW3().comp(a,b);
          return result;
     }
     };

   // this is where I need help
}
}

How would I use the comparator to sort the list??

I was thinking maybe something along the lines of Collections.sort(l, c)

2 Answers 2

1

yes, you can use Collections.sort( list, comparator ) or a TreeSet which sorts the collection upon adding of new elements

SortedSet ss = new TreeSet( comparator );
ss.add( someObj0 );
.... 
ss.add( someObjn );
List sortedList = new ArrayList( ss );
Sign up to request clarification or add additional context in comments.

Comments

0

Yes.

YourComparitorClass comparitor = new YourComparitorClass();
List<SomeType> list = ... initialize this somehow that makes sense

Collections.sort(list, comparitor);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.