简体   繁体   English

在Java中首先按长度然后按字母顺序对数组进行排序

[英]Sort array first by length then alphabetically in Java

How can I sort an array first by length, then alphabetically?如何首先按长度对数组进行排序,然后按字母顺序排序?

I have a list of things with numbers on them, and I am currently getting:我有一个带有数字的东西清单,我目前得到:

Something1 Something10 Something2 Something3某物1 某物10 某物2 某物3

Whereas I want to get:而我想得到:

Something1 Something2 Something3 Something10某物1 某物2 某物3 某物10

public class MyComparator implements Comparator<String>{
    @Override
    public int compare(String o1, String o2) {  
      if (o1.length() > o2.length()) {
         return 1;
      } else if (o1.length() < o2.length()) {
         return -1;
      }
      return o1.compareTo(o2);
    }
}

Then use:然后使用:

Collections.sort(yourList, new MyComparator());

Here's a concise Java 8 solution:这是一个简洁的 Java 8 解决方案:

List<String> list = Arrays.asList("Something1", "Something10", "Something2", "Something3");
list.sort(Comparator.comparing(String::length).thenComparing(String::compareTo));

Or, case-insensitive version:或者,不区分大小写的版本:

list.sort(Comparator.comparing(String::length).thenComparing(String::compareToIgnoreCase));

创建一个 Comparator,首先按长度进行比较,如果长度相同,则使用 String.compareTo()。

Sorting first by length and then lexically will work ONLY if the string prefixes (ie the part before the number) is the same length in all cases.仅当字符串前缀(即数字之前的部分)在所有情况下长度相同时,首先按长度排序,然后按词法排序才有效。 I believe you may really want to write a comparator that separates the string and numeric parts and sorts alphabetically on the string and numerically on the number part.我相信您可能真的想编写一个比较器来分隔字符串和数字部分,并在字符串上按字母顺序排序,在数字部分上按数字排序。

By using lambda, The java program looking like.通过使用 lambda,java 程序看起来像。

import java.util.Arrays;
import java.util.List;

public class Test1 {

    public static void main(String[] args) {
        
        String str = "This is am example";
        List<String> strl = Arrays.asList(str.split(" "));
        strl.sort( (o1,o2)->{
            if(o1.length() > o2.length())      return 1;
            else if(o1.length() < o2.length()) return -1;
            else                               return o1.compareTo(o2);
        });
        System.out.println(strl);

    }
}

Define a class to hold your item in. Seems like you want it to be a String.定义一个类来保存您的项目。似乎您希望它是一个字符串。

For that class, you need to define the Comparable interface and put the logic to compare in its abstract method.对于该类,您需要定义 Comparable 接口并将要比较的逻辑放在其抽象方法中。

int compareTo(T o)

For example:例如:

class MyString extends String
{
  @Override
  int compareTo(Object obj)
  {
    // put your logic in here. 
    // Return -1 if this is "less than" obj. 
    // Return 0 if this is equal to obj
    // Return 1 if this is "greater than" obj.

    // Test length first
    if (length() < obj.length())
      return -1;
    if (length() > obj.length())
      return 1;

    // Lengths are the same, use the alphabetical compare defined by String already
    return super.compareTo(obj);
   }
}

Disclaimer, I didn't actually test this code, but it should be close to what you want.免责声明,我实际上并没有测试这段代码,但它应该接近你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM