使用比较器对列表进行排序 import java.util.*; 公共级CW3{ 私有静态HashMapmap=newhashmap(); int comp(字符串s1、字符串s2){ int i1=map.get(s1); int i2=map.get(s2); 如果(i1

使用比较器对列表进行排序 import java.util.*; 公共级CW3{ 私有静态HashMapmap=newhashmap(); int comp(字符串s1、字符串s2){ int i1=map.get(s1); int i2=map.get(s2); 如果(i1,java,Java,如何使用比较器对列表进行排序 我在想可能是类似于收集的东西。排序(l,c)是的 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

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

我在想可能是类似于收集的东西。排序(l,c)

是的

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
}
}
YourComparitorClass comparitor=新建YourComparitorClass();
列表=。。。以某种方式初始化它是有意义的
集合。排序(列表、比较器);

是的,您可以使用
集合.排序(列表,比较器)
树集
在添加新元素时对集合进行排序

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

Collections.sort(list, comparitor);
SortedSet ss = new TreeSet( comparator );
ss.add( someObj0 );
.... 
ss.add( someObjn );
List sortedList = new ArrayList( ss );