按长度差对字符串的 ArrayList 进行排序

发布于 2024-12-07 00:14:27 字数 459 浏览 0 评论 0原文

我想按长度对字符串 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)

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

泼猴你往哪里跑 2024-12-14 00:14:27

使用自定义比较器:

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) 对列表进行排序。

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).

ゝ杯具 2024-12-14 00:14:27

如果你使用 java 8 你也可以尝试使用这个 lambda

packages.sort(Comparator.comparingInt(String::length));

If you are using java 8 you can also try using this lambda

packages.sort(Comparator.comparingInt(String::length));
影子的影子 2024-12-14 00:14:27

如果您使用的是 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()));

If you're using Java 8+ you can use a lambda expression to implement (@Barend's answer as) the comparator

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()));
卖梦商人 2024-12-14 00:14:27
  • 字符串按升序排列
class StringLengthListSort implements Comparator<String>{

    @Override
    public int compare(String s1, String s2) {
    return s1.length() - s2.length();
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
    List<String> list = new ArrayList<String>();
    StringLengthListSort ss = new StringLengthListSort();
    list.add("ram");
    list.add("rahim");
    list.add("ramshyam");
    Collections.sort(list, ss);
    System.out.println(list);
    }

}
  • String in Ascending order
class StringLengthListSort implements Comparator<String>{

    @Override
    public int compare(String s1, String s2) {
    return s1.length() - s2.length();
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
    List<String> list = new ArrayList<String>();
    StringLengthListSort ss = new StringLengthListSort();
    list.add("ram");
    list.add("rahim");
    list.add("ramshyam");
    Collections.sort(list, ss);
    System.out.println(list);
    }

}
菩提树下叶撕阳。 2024-12-14 00:14:27

您可以使用 Collections.sort() 接受显式 比较器

You'd do this with the version of Collections.sort() that takes an explicit Comparator.

深爱成瘾 2024-12-14 00:14:27

我有一个通过 lambda 表达式解决的类似问题:

listBeforeSorting.sort((s1, s2) -> s1.length() - s2.length());

这样,我们将得到按长度排序(升序)列表。

I have a similar problem solved by lambda expression:

listBeforeSorting.sort((s1, s2) -> s1.length() - s2.length());

This way, we will get sorted-by-length(ascending order) list.

£冰雨忧蓝° 2024-12-14 00:14:27
Collections.sort(list, (a, b)->Integer.compare(a.length(), b.length()));
Collections.sort(list, (a, b)->Integer.compare(a.length(), b.length()));
瑕疵 2024-12-14 00:14:27

使用自定义比较器是正确的。这是实现它的一种方法:

    Comparator c = new Comparator<String>()
    {
        public int compare(String s1, String s2) {
            return Integer.compare(s1.length(), s2.length());
        }
    };
    Collections.sort(results, c);
    return results;

The use of a custom comparator is correct. This is one way to implement it:

    Comparator c = new Comparator<String>()
    {
        public int compare(String s1, String s2) {
            return Integer.compare(s1.length(), s2.length());
        }
    };
    Collections.sort(results, c);
    return results;
萌︼了一个春 2024-12-14 00:14:27

使用 Java8 解决方案简单,仅包含比较器和方法参考:
Stream.of(list).flatMap(Collection::stream).sorted(Comparator.comparing(String::length)).collect(toList());

simple with Java8 solution with Comparator and Method reference only:
Stream.of(list).flatMap(Collection::stream).sorted( Comparator.comparing( String::length)).collect(toList());

贵在坚持 2024-12-14 00:14:27
The shortest code for this-

public static void main(String... str) {
        List.of("am", "I", "Best", "the").stream().sorted((a, b) -> a.length() - b.length())
                .forEach(System.out::println);
    }
The shortest code for this-

public static void main(String... str) {
        List.of("am", "I", "Best", "the").stream().sorted((a, b) -> a.length() - b.length())
                .forEach(System.out::println);
    }
隐诗 2024-12-14 00:14:27
List<String> list = Arrays.asList("geeksforgeeks", "geeksfor", "geeks");
Collections.sort(list, new Comparator<String>(){
       public int compare(String s1, String s2){
                return s1.length() - s2.length();
       }
});
List<String> list = Arrays.asList("geeksforgeeks", "geeksfor", "geeks");
Collections.sort(list, new Comparator<String>(){
       public int compare(String s1, String s2){
                return s1.length() - s2.length();
       }
});
半寸时光 2024-12-14 00:14:27

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

String[] strArr = { "Apples","CSS", "HTML", "Oracle", "Dart"};
    
List<String> result = Arrays.asList(strArr).stream().sorted( (str1,str2) ->  str1.length() - str2.length()).collect(Collectors.toList());
    
System.out.println(result); // output in Ascending Order : [CSS, HTML, Dart, Apples, Oracle]

Sort the list of string by length using java8

String[] strArr = { "Apples","CSS", "HTML", "Oracle", "Dart"};
    
List<String> result = Arrays.asList(strArr).stream().sorted( (str1,str2) ->  str1.length() - str2.length()).collect(Collectors.toList());
    
System.out.println(result); // output in Ascending Order : [CSS, HTML, Dart, Apples, Oracle]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文