由长字符串排序的ArrayList [英] Sort ArrayList of strings by length

查看:106
本文介绍了由长字符串排序的ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要订​​购由长度字符串的ArrayList,而不仅仅是数字顺序。

比方说,列表中包含了这些话:

 黄瓜
aeronomical
培根

伸缩式
fantasmagorical

他们需要得到他们的长度差责令其特殊字符串,例如:

 智能

所以,最后的名单看起来像这样(括号中的差异):

  aeronomical(0)
伸缩(1)
fantasmagorical(3) - 正分歧优先?其实并不重要
黄瓜(3)
熏肉(6)
茶(8)


解决方案

使用自定义的比较:

 公共类MyComparator实现了java.util.Comparator<串GT; {    私人诠释referenceLength;    公共MyComparator(String引用){
        超();
        this.referenceLength = reference.length();
    }    公众诠释比较(字符串S1,S2的字符串){
        INT DIST1 = Math.abs(s1.length() - referenceLength);
        INT dist2 = Math.abs(s2.length() - referenceLength);        返回DIST1 - dist2;
    }
}

然后使用排序列表 java.util.Collections.sort(列表,比较器)

I want to order an ArrayList of strings by length, but not just in numeric order.

Say for example, the list contains these words:

cucumber
aeronomical
bacon
tea
telescopic
fantasmagorical

They need to be ordered by their difference in length to a special string, for example:

intelligent

So the final list would look like this (difference in brackets):

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

解决方案

Use a custom comparator:

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;
    }
}

Then sort the list using java.util.Collections.sort(List, Comparator).

这篇关于由长字符串排序的ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆