Java自定义比较器,用于对字符串数组进行排序

时间:2020-05-23 04:26:58

标签: java arrays sorting comparator

在这里,我试图将字符串中具有开始和结束字母相同的单词排序。应该在适当的位置进行排序,否则不要打扰。

import java.util.*;
public class MyClass {
public static void main(String args[]) {
  String arr[]={"zpppz","poop","zllo","bob","yea"};
  Arrays.sort(arr , new Comparator<String>(){
      public int compare(String a ,String b){
          if((a.charAt(0) == a.charAt(a.length()-1 ) )&&(b.charAt(0)==b.charAt(b.length()-1 ) )  ){
           return a.compareTo(b);
          }
          return 0;
      }
  } );
  for(String s: arr ) System.out.println(s);
}
} 

预期输出: “鲍勃” “船尾” “ zllo” “ zpppz” 是的 但即时通讯输出为: “鲍勃” “船尾” “ zpppz” “ zllo” 是的

2 个答案:

答案 0 :(得分:2)

如何将“比较器”与“选择排序”之类的东西一起使用?

public class Test {
    public static void main(String args[]) {
        String arr[]={"zpppz","poop","zllo","bob","yea"};
        Comparator<String> comparator = new Comparator<>() {
            public int compare(String a, String b) {
                if ((a.charAt(0) == a.charAt(a.length() - 1)) && (b.charAt(0) == b.charAt(b.length() - 1))) {
                    return a.compareTo(b);
                }
                return 0;
            }
        };
        selectionSort(arr, comparator);
    }

    static <T> void selectionSort(T[] a, Comparator<T> c) {
        for (int i = 0; i < a.length; i++) {
            for (int j = i; j < a.length; j++) {
                if (c.compare(a[i], a[j]) > 0) {
                    T hold = a[i];
                    a[i] = a[j];
                    a[j] = hold;
                }
            }
        }
    }
}

结果:[bob,poop,zllo,zpppz,是]

答案 1 :(得分:1)

以下代码可以满足您的需求,但不使用Comparator
如果不可接受,请告诉我,我将删除此答案。

private static boolean isCandidate(String word) {
    boolean candidate = false;
    if (word != null && word.length() > 0) {
        candidate = word.charAt(0) == word.charAt(word.length() - 1);
    }
    return candidate;
}
/**********************************************************/
String arr[] = {"zpppz", "poop", "zllo", "bob", "yea"};
List<Integer> indexList = new ArrayList<>();
List<String> words2sort = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
    if (isCandidate(arr[i])) {
        indexList.add(Integer.valueOf(i));
        words2sort.add(arr[i]);
    }
}
if (words2sort.size() > 0) {
    Collections.sort(words2sort);
    int index = 0;
    String[] sorted = new String[arr.length];
    for (int i = 0; i < arr.length; i++) {
        if (index < indexList.size() && indexList.get(index).intValue() == i) {
            sorted[i] = words2sort.get(index);
            index++;
        }
        else {
            sorted[i] = arr[i];
        }
    }
    System.out.println(Arrays.asList(sorted));
}

运行上述代码的结果:

[bob, poop, zllo, zpppz, yea]