简体   繁体   English

使用比较器对列表进行排序

[英]Sorting a list using a comparator

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) 我在想也许与Collections.sort(l,c)类似的东西

yes, you can use Collections.sort( list, comparator ) or a TreeSet which sorts the collection upon adding of new elements 是的,您可以使用Collections.sort( list, comparator )TreeSet在添加新元素时对集合进行排序

SortedSet ss = new TreeSet( comparator );
ss.add( someObj0 );
.... 
ss.add( someObjn );
List sortedList = new ArrayList( ss );

Yes. 是。

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

Collections.sort(list, comparitor);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM