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

马特:

我想按长度顺序排列一个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)
Barend:

使用自定义比较器:

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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

按降序对字符串列表进行排序(根据长度)

按字符串长度降序对字符串列表进行排序,请勿更改列表

按字符串长度降序对字符串列表进行排序,不会更改列表

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

如何按长度降序对字符串列表的内容进行排序?

如何在python中按长度对二维字符串列表进行排序?

按整数列表对字符串列表进行排序

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

在Java中按字符对字符串列表进行排序

如何按字母顺序对字符串列表进行排序?

按多个参数对字符串列表进行排序

按降序对字符串列表进行自然排序

Dart:按频率对字符串列表进行排序

按数字部分的顺序对字符串列表进行排序

按索引对字符串列表进行排序

如何按多种条件对字符串列表进行排序

按出现频率对(嵌套的)字符串列表进行排序

按map值对字符串列表进行排序

如何按最高编号对字符串列表进行排序

按数字排序字符串列表

如何对字符串列表进行排序

如何对字符串列表进行排序?

按字符串的一部分对字符串列表进行排序

使用lambda函数按两个子字符串对字符串列表进行排序

Python:如何按子字符串相关性对字符串列表进行排序?

按Java中最常见字符的顺序对字符串列表进行排序

如何按某个字符的数量对字符串列表进行排序?

按子字符串排序字符串列表

无法在C中按字母顺序对字符串列表进行排序