按长度对字符串进行排序列表

2022-09-01 19:48:59

我想按长度对字符串的 ArrayList 进行排序,而不仅仅是按数字顺序排序。

例如,列表包含以下单词:

cucumber
aeronomical
bacon
tea
telescopic
fantasmagorical

它们需要按其长度与特殊字符串的长度差进行排序,例如:

intelligent

因此,最终列表将如下所示(括号中的差异):

aeronomical     (0)
telescopic      (1)
fantasmagorical (3) - give priority to positive differences? doesn't really matter
cucumber        (3)
bacon           (6)
tea             (8)

答案 1

使用自定义比较器:

public class MyComparator implements java.util.Comparator<String> {

    private int referenceLength;

    public MyComparator(String reference) {
        super();
        this.referenceLength = reference.length();
    }

    public int compare(String s1, String s2) {
        int dist1 = Math.abs(s1.length() - referenceLength);
        int dist2 = Math.abs(s2.length() - referenceLength);

        return dist1 - dist2;
    }
}

然后使用 对列表进行排序。java.util.Collections.sort(List, Comparator)


答案 2

如果您使用的是Java 8+,则可以使用lambda表达式来实现(@Barend的答案)比较器

List<String> strings = Arrays.asList(new String[] {"cucumber","aeronomical","bacon","tea","telescopic","fantasmagorical"});
strings.sort((s1, s2) -> Math.abs(s1.length() - "intelligent".length()) - Math.abs(s2.length() - "intelligent".length()));

推荐