使用比较器排序字符串长度

时间:2011-12-26 04:12:43

标签: java

在尝试根据元素字符串长度对数组进行排序时,我遇到了编译错误。我有一套开头,

Set<String> arraycat = new HashSet<String>();
//add contents to arraycat
String[] array = arraycat.toArray(new String[0]);
//array looks like this now:
//array=[cat,cataaaa,cataa,cata,cataaa]

我理想的是要排序到

array=[cat,cata,cataa,cataaa,cataaaa]

所以我有一个类型为

的比较器
class comp implements Comparator {

    public int compare(String o1, String o2) {
        if (o1.length() > o2.length()) {
            return 1;
        } else if (o1.length() < o2.length()) {
            return -1;
        } else {
            return 0;
        }
    }
}

然后我通过

调用该类
Collections.sort(array, new comp());

但是,它引发了两个编译错误:

comp is not abstract and does not override abstract method   compare(java.lang.Object,java.lang.Object) in java.util.Comparator
class comp implements Comparator {
^
testa.java:59: cannot find symbol
symbol  : method sort(java.lang.String[],comp)
location: class java.util.Collections
Collections.sort(array, new comp());
^2 errors

我很感激任何解决问题的线索。

6 个答案:

答案 0 :(得分:15)

您需要为Comparator指定一个类型参数才能使您的实现正常工作。

class comp implements Comparator<String> {
  public int compare(String o1, String o2) {
    if (o1.length() > o2.length()) {
      return 1;
    } else if (o1.length() < o2.length()) {
      return -1;
    } else {
      return 0;
    }
  }
}

在Java 1.7及更高版本中,您还可以将此方法的主体简化为:

class comp implements Comparator<String> {
  public int compare(String o1, String o2) {
    return Integer.compare(o1.length(), o2.length());
  }
}

此外,Collections.sortList个对象进行排序。由于您要对数组进行排序,因此应使用Arrays.sort

Arrays.sort(array, new comp());

答案 1 :(得分:7)

如果数据源为Arrays.sort(),则需要使用array方法。

例如,

String []array={"first","second","third","six"};

Arrays.sort(array,new Comparator<String>()
{
  public int compare(String s1,String s2)
   {
    return s1.length() - s2.length();
    }
});

或者将数组转换为List以使用Collections.sort()方法,

Collections.sort(Arrays.asList(array),new Comparator<String>()
{
  public int compare(String s1,String s2)
   {
    return s1.length() - s2.length();
    }
});

答案 2 :(得分:2)

应该是

class comp implements Comparator<String> { ...

甚至更好

Collections.sort(array, new Comparator<String> { ...

(甚至没有命名仅使用过一次的类)

答案 3 :(得分:2)

One Liners

升序

Arrays.sort(words, Comparator.comparingInt(String::length));

降序

Arrays.sort(words, Comparator.comparingInt(String::length).reversed());

答案 4 :(得分:0)

我最近有类似的任务,我将为您提供一个额外的例子。

import java.util.Arrays;
import java.util.Comparator;
//for more information: http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html

/**
 *
 * @author Xilef
 */
public class StringKorter implements Comparator<String> {
    @Override
    public int compare(String s1, String s2){
        if (s1.length() > s2.length())
         return 1;
        else if (s1.length() < s2.length())
         return -1;
        else return 0;
    }
    public static void main(String[] args) {
        String[] woorden = { "boot", "kinderen", "stoel", "volwassenen", "ei", "stoel", "kop", "zeshoek", "stoel", "ei" };
        System.out.println("woorden: " + Arrays.toString(woorden));//before sorting by length
        Arrays.sort(woorden, new StringKorter());
        System.out.println("Array woorden after sorting by length: " + Arrays.toString(woorden));
    }
}

答案 5 :(得分:0)

使用流和比较器实现相同的效果,如下所示-

Arrays.stream(array)
      .sorted(Comparator.comparingInt(String::length))
      .forEach(a -> System.out.print(a + " "));