Java程序以升序排序版本字符串。

huangapple go评论113阅读模式
英文:

Java program to sort a versioning string in an ascending order

问题

Sure, here is the translated code snippet:

我有一个包含版本字符串的列表类似于这样

List<String> versions_list = Arrays.asList("1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2");

我想对它进行排序所以结果应该类似于这样

["1.0.0", "1.0.2", "1.0.12", "1.1.2", "1.3.3"]

如何在Java中实现这个
英文:

I have a list containing version strings, such as things:

List&lt;String&gt; versions_list = Arrays.asList(&quot;1.1.2&quot;, &quot;1.0.0&quot;, &quot;1.3.3&quot;, &quot;1.0.12&quot;, &quot;1.0.2&quot;);

I would like to sort it, so the result would be something like this:

[&quot;1.0.0&quot;, &quot;1.0.2&quot;, &quot;1.0.12&quot;, &quot;1.1.2&quot;, &quot;1.3.3&quot;]

How to do this in Java.

答案1

得分: 5

以下是翻译好的代码部分:

这里是一个*现代*的解决方案使用`Comparator.comparing`来构建一个版本字符串比较器基于现有的标准库`Arrays.compare(int[])`方法

List<String> versionList = Arrays.asList("1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2");

Pattern pattern = Pattern.compile("\\.");
Comparator<String> versionComparator = Comparator.comparing(
    str -> pattern.splitAsStream(str)
        .mapToInt(Integer::parseInt)
        .toArray(),
    Arrays::compare);
versionList.sort(versionComparator);

System.out.println(versionList);
英文:

Here is a modern solution, using Comparator.comparing to build a version string comparator, based on the pre-existing standard library Arrays.compare(int[]) method.

    List&lt;String&gt; versionList = Arrays.asList(&quot;1.1.2&quot;, &quot;1.0.0&quot;, &quot;1.3.3&quot;, &quot;1.0.12&quot;, &quot;1.0.2&quot;);

    Pattern pattern = Pattern.compile(&quot;\\.&quot;);
    Comparator&lt;String&gt; versionComparator = Comparator.comparing(
        str -&gt; pattern.splitAsStream(str)
            .mapToInt(Integer::parseInt)
            .toArray(),
        Arrays::compare);
    versionList.sort(versionComparator);
    
    System.out.println(versionList);

答案2

得分: 1

您可以使用Comparator来实现如下所示:

List<String> sorted = List.of("1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2")
        .stream()
        .sorted((s1, s2) -> {
            String[] s1Parts = s1.split("\\.");
            String[] s2Parts = s2.split("\\.");

            Integer[] s1IntParts = Arrays.stream(s1Parts).map(Integer::parseInt).toArray(Integer[]::new);
            Integer[] s2IntParts = Arrays.stream(s2Parts).map(Integer::parseInt).toArray(Integer[]::new);

            int comparisonResult = -1;
            for (int i = 0; i < 3; i++) {
                comparisonResult = Integer.compare(s1IntParts[i], s2IntParts[i]);
                if (comparisonResult != 0) {
                    break;
                }
            }
            return comparisonResult;
        })
        .collect(Collectors.toList());
英文:

You can do this using Comparator as shown below:

    List&lt;String&gt; sorted = List.of(&quot;1.1.2&quot;, &quot;1.0.0&quot;, &quot;1.3.3&quot;, &quot;1.0.12&quot;, &quot;1.0.2&quot;)
            .stream()
            .sorted((s1, s2) -&gt; {
                String[] s1Parts = s1.split(&quot;\\.&quot;);
                String[] s2Parts = s2.split(&quot;\\.&quot;);

                Integer[] s1IntParts = Arrays.stream(s1Parts).map(Integer::parseInt).toArray(Integer[]::new);
                Integer[] s2IntParts = Arrays.stream(s2Parts).map(Integer::parseInt).toArray(Integer[]::new);

                int comparisonResult = -1;
                for (int i=0; i&lt;3; i++) {
                    comparisonResult = Integer.compare(s1IntParts[i], s2IntParts[i]);
                    if (comparisonResult != 0) {
                        break;
                    }
                }
                return comparisonResult;
            })
            .collect(Collectors.toList());

答案3

得分: 1

Sure, here's the translated code:

public static void main(String[] args) {
    String[] versions_list = {"1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2"};
    Arrays.sort(versions_list, (o1, o2) -> {
        String[] str1 = o1.split("\\.");
        String[] str2 = o2.split("\\.");
        if (!Integer.valueOf(str1[0]).equals(Integer.valueOf(str2[0])))
            return Integer.valueOf(str1[0]) - Integer.valueOf(str2[0]);
        if (!Integer.valueOf(str1[1]).equals(Integer.valueOf(str2[1])))
            return Integer.valueOf(str1[1]) - Integer.valueOf(str2[1]);
        return Integer.valueOf(str1[2]) - Integer.valueOf(str2[2]);
    });
    for (String str : versions_list) {
        System.out.println(str);
    }
}

Output: 1.0.0 1.0.2 1.0.12 1.1.2 1.3.3, you also use cycle to do it!

英文:
public static void main(String[] args) {
    String[] versions_list = {&quot;1.1.2&quot;, &quot;1.0.0&quot;, &quot;1.3.3&quot;, &quot;1.0.12&quot;, &quot;1.0.2&quot;};
    Arrays.sort(versions_list, (o1, o2) -&gt; {
        String[] str1 = o1.split(&quot;\\.&quot;);
        String[] str2 = o2.split(&quot;\\.&quot;);
        if (!Integer.valueOf(str1[0]).equals(Integer.valueOf(str2[0])))
            return Integer.valueOf(str1[0]) - Integer.valueOf(str2[0]);
        if (!Integer.valueOf(str1[1]).equals(Integer.valueOf(str2[1])))
            return Integer.valueOf(str1[1]) - Integer.valueOf(str2[1]);
        return Integer.valueOf(str1[2]) - Integer.valueOf(str2[2]);
    });
    for (String str : versions_list) {
        System.out.println(str);
    }
}

sorry,I wirte code again
output:1.0.0 1.0.2 1.0.12 1.1.2 1.3.3, you also use cycle to do it!

答案4

得分: 0

以下是您要翻译的代码部分:

假设:

List<String> versions = Arrays.asList("1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2");

只要默认比较器不能应用于此类型的字符串,就应该使用自定义的Comparator,否则数字将不会按数字方式排序(例如,12 被认为比 2 低。

使用匿名类:

versions.sort(new Comparator<String>() {
    @Override
    public int compare(final String l, final String r) {
        String[] left = l.split("\\.");
        String[] right = r.split("\\.");
        int iterableLength = Math.min(left.length, right.length);
        for (int i=0; i<iterableLength; i++) {
            if (!left[i].equals(right[i])) {
                return Integer.parseInt(left[i]) - Integer.parseInt(right[i]);
            }
        }
        return 0;
    }
});

... 使用 Lambda 表达式 ...

versions.sort((l, r) -> {
    String[] left = l.split("\\.");
    String[] right = r.split("\\.");
    int iterableLength = Math.min(left.length, right.length);
    for (int i=0; i<iterableLength; i++) {
        if (!left[i].equals(right[i])) {
            return Integer.parseInt(left[i]) - Integer.parseInt(right[i]);
        }
    }
    return 0;
});

这是一种使用正则表达式将版本表示分成三个独立部分的非常直接的解决方案。每个与另一个不相等的部分都需要进行数字比较,因此需要使用 Integer.parseInt(String)

英文:

Assuming:

List&lt;String&gt; versions = Arrays.asList(&quot;1.1.2&quot;, &quot;1.0.0&quot;, &quot;1.3.3&quot;, &quot;1.0.12&quot;, &quot;1.0.2&quot;);

You should use a custom Comparator as long as the default comparator cannot be applied to this type of the String, otherwise the numbers will not be sorted numerically (ex, 12 is considered lower than 2.

versions.sort(new Comparator&lt;String&gt;() {
	@Override
	public int compare(final String l, final String r) {
		String[] left = l.split(&quot;\\.&quot;);
		String[] right = r.split(&quot;\\.&quot;);
		int iterableLength = Math.min(left.length, right.length);
		for (int i=0; i&lt;iterableLength; i++) {
			if (!left[i].equals(right[i])) {
				return Integer.parseInt(left[i]) - Integer.parseInt(right[i]);
			}
		}
		return 0;
	}
});

... using a lambda expression ...

versions.sort((l, r) -&gt; {
	String[] left = l.split(&quot;\\.&quot;);
	String[] right = r.split(&quot;\\.&quot;);
	int iterableLength = Math.min(left.length, right.length);
	for (int i=0; i&lt;iterableLength; i++) {
		if (!left[i].equals(right[i])) {
			return Integer.parseInt(left[i]) - Integer.parseInt(right[i]);
		}
	}
	return 0;
});

This is a very straightforward solution using Regex to split the version notation into 3 separate parts. Each part not equal to another is a subject for the numeric comparison, hence Integer.parseInt(String) is needed.

答案5

得分: 0

这里是使用Comparator的lambda表达式的一种方法,用于处理不同长度的版本号。以下是代码的翻译:

Comparator<String> comp = (a, b) -> {
    String[] aa = a.split("\\.");
    String[] bb = b.split("\\.");
    int r = 0;
    for (int i = 0; i < Math.min(aa.length, bb.length); i++) {
        r = Integer
                .compare(Integer.valueOf(aa[i]), Integer.valueOf(bb[i]));
        if (r != 0) {
            return r;
        }
    }
    return Integer.compare(aa.length, bb.length);
};

List<String> versions_list = Arrays.asList("1.1.2", "1.0.0",
        "1.3.3", "1.0.12", "1.0.0.12", "1.1.0.2", "1.0.2", "1.2.1.2.3");
versions_list.sort(comp);
System.out.println(versions_list);

输出结果:

[1.0.0, 1.0.0.12, 1.0.2, 1.0.12, 1.1.0.2, 1.1.2, 1.2.1.2.3, 1.3.3]
英文:

Here is one way using a lambda of the Comparator. Takes care of varying length version ids.

Comparator&lt;String&gt; comp = (a, b) -&gt; {
	String[] aa = a.split(&quot;\\.&quot;);
	String[] bb = b.split(&quot;\\.&quot;);
	int r = 0;
	for (int i = 0; i &lt; Math.min(aa.length, bb.length); i++) {
		r = Integer
				.compare(Integer.valueOf(aa[i]),Integer.valueOf(bb[i]));
		if (r != 0) {
			return r;
		}
	}
	return Integer.compare(aa.length, bb.length);
};
			
List&lt;String&gt; versions_list = Arrays.asList(&quot;1.1.2&quot;, &quot;1.0.0&quot;,
		&quot;1.3.3&quot;, &quot;1.0.12&quot;, &quot;1.0.0.12&quot;, &quot;1.1.0.2&quot;, &quot;1.0.2&quot;, &quot;1.2.1.2.3&quot;);
versions_list.sort(comp);
System.out.println(versions_list);

Prints

[1.0.0, 1.0.0.12, 1.0.2, 1.0.12, 1.1.0.2, 1.1.2, 1.2.1.2.3, 1.3.3]


</details>



huangapple
  • 本文由 发表于 2020年8月1日 22:33:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/63206366.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定