用于在两个给定值中显示更高版本的Java代码

时间:2017-06-23 10:45:31

标签: java

用于在两个给定值中显示更高版本的Java代码。

Version1=7.3.4.2.5.9
Version2=7.3.2.3.8.1

它应该返回版本1的值,因为它大于版本2.

我尝试根据。(点)分割数字,然后逐个比较。但它似乎不是一个好方法。还有其他方法或建议吗?

我的方法

class App {
public static void main(String args[]) {
    String Version1 = "7.3.4.02.5.9";
    String Version2 = "7.3.4.3.8.1";
    String[] v1Split = Version1.split("\\.");
    String[] v2Split = Version2.split("\\.");

    for (int i = 0; i < v1Split.length; i++) {
        if (v2Split != null) {
            int v1 = Integer.parseInt(v1Split[i]);
            int v2 = Integer.parseInt(v2Split[i]);
            if (v1 > v2) {
                System.out.println(Version1);
                break;
            }
            if (v2 > v1) {
                System.out.println(Version2);
                break;
            }
            if (v1 == v2)
                continue;
        }
    }
}

}

3 个答案:

答案 0 :(得分:3)

您可以实现一个比较器,它将每个版本字符串拆分成多个部分,然后逐个比较相同位置的部分,返回第一个不等式。如果所有现有位置的零件相等,则包含更多零件的版本更大:

"1.2" < "1.3" < "1.3.1" == "1.3.1" < "1.3.1.1" < "1.4"

这是比较器:

class VersionComparator implements Comparator<String> {
    @Override
    public int compare(String version1, String version2) {
        List<String> v1 = Arrays.asList(version1.split("\\."));
        List<String> v2 = Arrays.asList(version2.split("\\."));
        return IntStream.range(0, Math.min(v1.size(), v2.size()))
                .map(i -> Integer.valueOf(v1.get(i)).compareTo(Integer.valueOf(v2.get(i))))
                .filter(i -> i != 0)
                .findFirst()
                .orElse(Integer.compare(v1.size(), v2.size()));
    }
}

示例和工作证明:

public static void main(String[] args) {
    String[] versions = new String[]{
            "7.3.4.2.5.9",
            "7.3.2.3.8.1",
            "7.2",
            "7.3.0",
            "7.13.0",
            "6.4.2.3.5",
            "7.3.2.3",
            "7.3.4.2.5.9.1",
    };

    Stream.of(versions)
            .sorted(new VersionComparator())
            .forEach(System.out::println);
}

结果:

6.4.2.3.5
7.2
7.3.0
7.3.2.3
7.3.2.3.8.1
7.3.4.2.5.9
7.3.4.2.5.9.1
7.13.0

答案 1 :(得分:2)

下面的方法将返回两者的较大版本。希望这会有所帮助,如果不起作用,请告诉我任何情况。尝试了一些,它运作良好。

private static String getGreater(String Version1, String Version2){
        //Splitting numbers to String array based on .
        String[] v1 = Version1.split("\\.");
        String[] v2 = Version2.split("\\.");

        //Start with any one of the splitted array
        for(int i = 0;i < v1.length;i++){
            int a1 = Integer.parseInt(v1[i]);
            int a2 = Integer.parseInt(v2[i]);
            //Start from left to right, Convert to int and then check for which is greater. When you find greater return specified version
            if(a1 > a2){
                return Version1;
            }else if(a1 < a2){
                return Version2;
            }
        }
        //If you reach here either one of the version is null/blank  or both are same so return anythign. You might need to check at your end
        //that you don't send null or blanks to this method/
        return Version1;
    }

答案 2 :(得分:0)

您需要创建表示您尝试比较的版本的类Version,并使此类实现接口Comparable

   public final class Version implements Comparable<Version> {
    private final String versionString;

    public Version(String versionString) {
        this.versionString = versionString;
    }

    @Override
    public int compareTo(Version otherVersion) {
        Iterator<Integer> thisChunks = this.chunksIterator();
        Iterator<Integer> otherChunks = otherVersion.chunksIterator();
        while (thisChunks.hasNext()) {
            if (!otherChunks.hasNext()) break;
            int thisNumber = thisChunks.next();
            int otherNumber = otherChunks.next();
            if (thisNumber != otherNumber) {
                return thisNumber - otherNumber;
            }
        }
        return otherChunks.hasNext() ? -1 : 0;
    }

    private Iterator<Integer> chunksIterator() {
        List<Integer> chunks = new ArrayList<>();
        Arrays.stream(versionString.split("\\."))
                .forEach(chunk -> chunks.add(Integer.parseInt(chunk)));
        return chunks.iterator();
    }

    @Override
    public String toString() {
        return versionString;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Version version = (Version) o;

        return versionString != null ? versionString.equals(version.versionString) : version.versionString == null;
    }

    @Override
    public int hashCode() {
        return versionString != null ? versionString.hashCode() : 0;
    }
}

这里是这堂课的考试:

public class VersionTest {

    @Test
    public void shouldSortListWithTwoVersions() throws Exception {
        List<Version> versions = Arrays.asList(
                new Version("1.2.34.5"),
                new Version("1.2.5.7")
        );
        List<Version> expectedVersions = Arrays.asList(
                new Version("1.2.5.7"),
                new Version("1.2.34.5")
        );
        versions.sort(Comparator.naturalOrder());
        Assert.assertEquals(expectedVersions, versions);
    }

    @Test
    public void shouldSortListWithManyVersions() throws Exception {
        List<Version> versions = Arrays.asList(
                new Version("7.13.0"),
                new Version("7.3.2.3"),
                new Version("7.3.2.3.8.1"),
                new Version("6.4.2.3.5"),
                new Version("7.2"),
                new Version("7.3.0"),
                new Version("7.3.4.2.5.9"),
                new Version("7.3.4.2.5.9.1")
        );
        List<Version> expectedVersions = Arrays.asList(
                new Version("6.4.2.3.5"),
                new Version("7.2"),
                new Version("7.3.0"),
                new Version("7.3.2.3"),
                new Version("7.3.2.3.8.1"),
                new Version("7.3.4.2.5.9"),
                new Version("7.3.4.2.5.9.1"),
                new Version("7.13.0")
        );
        versions.sort(Comparator.naturalOrder());
        Assert.assertEquals(expectedVersions, versions);
    }

}

假设您的类路径中有junit

如果您认为解析和转换字符串是脏的方式,并且当您找到更好的方法时,您可以无缝地替换它,因为这是您的类Version的实现细节。