简体   繁体   English

在 Java 中比较版本的最简洁方法

[英]Most concise way of comparing versions in Java

Let's say I have a version of the form of major.minor.patch , eg 1.2.3 , and I want to compare it to another version 1.1.5 , as 2 > 1 the first version is greater than the second.假设我有一个major.minor.patch形式的版本,例如1.2.3 ,我想将它与另一个版本1.1.5进行比较,因为2 > 1第一个版本大于第二个版本。 How can I write the most concise & efficient compare function for the class Version :如何为class Version编写最简洁、最有效的比较函数:

class Version implements Comparable<Version> {

    int major
    int minor
    int patch

    @Override
    int compareTo(Version otherVersion) {
        // ... TODO
    }
}

Answers can be in Java or Groovy .答案可以是JavaGroovy

I would suggest adding getters for your three fields, then a Comparator using chained comparing functions.我建议为您的三个字段添加 getter,然后使用链式比较函数添加一个Comparator Like,喜欢,

public int getMajor() {
    return major;
}

public int getMinor() {
    return minor;
}

public int getPatch() {
    return patch;
}

private static final Comparator<Version> COMP = Comparator
        .comparingInt(Version::getMajor)
        .thenComparingInt(Version::getMinor)
        .thenComparingInt(Version::getPatch);

@Override
public int compareTo(Version otherVersion) {
    return COMP.compare(this, otherVersion);
}

groovy variant时髦的变种

@groovy.transform.ToString
class Version implements Comparable<Version> {

    int major
    int minor
    int patch

    @Override
    int compareTo(Version other) {
        major<=>other.major ?: minor<=>other.minor ?: patch<=>other.patch
    }
}

def v0=new Version(major:1,minor:2,patch:11)
def v1=new Version(major:1,minor:2,patch:22)
def v2=new Version(major:1,minor:2,patch:33)

assert v1.compareTo(v0)==1
assert v1.compareTo(v2)==-1
assert v1.compareTo(v1)==0

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

相关问题 Java中最简洁的方法是从“AlphaSuffix”中获取“Alpha”? - What's the most concise way in Java to get the “Alpha” out of “AlphaSuffix”? 在Java Spark中将2个集合加在一起的最简洁方法 - Most concise way to add together 2 collections in Java spark 最简洁的方法来读取Java中的文件/输入流的内容? - Most concise way to read the contents of a file/input stream in Java? 无需检查值两次即可表达此 Java 条件的最简洁方法 - Most concise way to express this Java conditional without checking a value twice 编写此 java 代码的最简洁/最佳方式是什么? - What's the most concise / best way to write this java code? 做“不包含”的最简洁方法? - Most concise way to do “not contained in”? 使用Java 8,打印文件中所有行的最优选和简洁方法是什么? - Using Java 8, what is the most preferred and concise way of printing all the lines in a file? 使用Java 8,创建排序和分组字符串列表的最简洁方法是什么 - Using Java 8, what is the most concise way of creating a sorted AND grouped list of Strings 使用Java 8,迭代地图中所有条目的最简洁方法是什么? - Using Java 8, what is the most concise way of iterating through all the entries in a map? 使用Java确定一个月内天数的最简洁方法(使用布尔运算符) - Most Concise Way to Determine Number of Days in a Month with Java (Using boolean Operators)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM