Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
926 views
in Technique[技术] by (71.8m points)

sorting - Java version number sort

String[] k1 = {"0.10", "0.2", "0.1", "0", "1.10", "1.2", "1.1", "1", "2.10", "2", "2.2", "2.1"};
double[] k2 = {0.10, 0.2, 0.1, 0, 1.10, 1.2, 1.1, 1, 2.10, 2, 2.2, 2.1};
Arrays.sort(k1);
Arrays.sort(k2);
System.out.println(Arrays.toString(k1));
System.out.println(Arrays.toString(k2));

output:

[0,   0.1, 0.10, 0.2,  1,   1.1, 1.10, 1.2,  2,   2.1, 2.10, 2.2]
[0.0, 0.1, 0.1,  0.2,  1.0, 1.1, 1.1,  1.2,  2.0, 2.1, 2.1,  2.2]

What I would like to have,

[0, 0.1, 0.2, 0.10, 1, 1.1, 1.2, 1.10, 2, 2.1, 2.2, 2.10]

First sort before decimals and after. Like 1, 1.1, 1.2, 1.10, 2, 2.1, etc.

How can I write a comparator for this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
2.1, 2.2, 2.10]

Since 2.10 is greater than 2.2 in this order it looks like a version number sort:

import java.util.Arrays;
import java.util.Comparator;

public class VersionNumberComparator implements Comparator<String> {
  @Override
  public int compare(String version1, String version2) {
    String[] v1 = version1.split("\.");
    String[] v2 = version2.split("\.");
    int major1 = major(v1);
    int major2 = major(v2);
    if (major1 == major2) {
      return minor(v1).compareTo(minor(v2));
    }
    return major1 > major2 ? 1 : -1;
  }

  private int major(String[] version) {
    return Integer.parseInt(version[0]);
  }

  private Integer minor(String[] version) {
    return version.length > 1 ? Integer.parseInt(version[1]) : 0;
  }

  public static void main(String[] args) {
    String[] k1 = { "0.10", "0.2", "0.1", "0", "1.10", "1.2", "1.1", "1",
        "2.10", "2", "2.2", "2.1" };
    Arrays.sort(k1, new VersionNumberComparator());
    System.out.println(Arrays.asList(k1));
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...