有没有一行代码可以在Java中创建一个包含一个或多个元素的SortedSet?

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

Is there a oneliner to create a SortedSet filled with one or multiple elements in Java?

问题

我只是在思考是否有一种更便捷的方式来创建一个SortedSet,比如在Java中使用的这个单行代码,而不是我目前在测试中正在使用的这个:

new TreeSet<>(Set.of(element1, element2));

类似于Apache Commons或类似库中的SortedSet.of(...)是否存在?

英文:

I am just asking myself if there is a more convenient way to create a SortedSet, e.g. a TreeSet in Java than the one liner I am currently using in tests:

new TreeSet&lt;&gt;(Set.of(element1, element2));

Something like SortedSet.of(...) maybe from Apache Commons or the like?

答案1

得分: 1

不确定在简单情况下(没有比较器)是否会被视为更好,但您可以使用来自Eclipse CollectionsSortedSets

SortedSet<Integer> sortedSet = SortedSets.mutable.of(1, 2, 3);
SortedSet<Integer> expected = new TreeSet<>(Set.of(1, 2, 3));

Assertions.assertEquals(expected, sortedSet);

SortedSet也可以使用Comparator在一行内创建:

SortedSet<Integer> reversed = 
    SortedSets.mutable.of(Comparator.reverseOrder(), 1, 2, 3);

SortedSet<Integer> expected = 
    new TreeSet<>(Comparator.reverseOrder());
expected.addAll(Set.of(1, 2, 3));

Assertions.assertEquals(expected, reversed);

注意:我是Eclipse Collections的贡献者。

英文:

Not sure if this will be considered better in the simple case (without Comparator), but you can use SortedSets from Eclipse Collections:

SortedSet&lt;Integer&gt; sortedSet = SortedSets.mutable.of(1, 2, 3);
SortedSet&lt;Integer&gt; expected =  new TreeSet&lt;&gt;(Set.of(1, 2, 3));

Assertions.assertEquals(expected, sortedSet);

A SortedSet can also be created in a one-liner with a Comparator.

SortedSet&lt;Integer&gt; reversed = 
    SortedSets.mutable.of(Comparator.reverseOrder(), 1, 2, 3);

SortedSet&lt;Integer&gt; expected = 
    new TreeSet&lt;&gt;(Comparator.reverseOrder());
expected.addAll(Set.of(1, 2, 3));

Assertions.assertEquals(expected, reversed);

Note: I am a committer for Eclipse Collections.

答案2

得分: -3

你可以使用类似于 Guava 的库:

import com.google.common.collect.Sets;
import java.util.SortedSet;

SortedSet&lt;Integer&gt; sortedSet = Sets.newTreeSet(ImmutableSet.of(1, 2, 3));
英文:

You can use a library like Guava:

import com.google.common.collect.Sets;
import java.util.SortedSet;

SortedSet&lt;Integer&gt; sortedSet = Sets.newTreeSet(ImmutableSet.of(1, 2, 3));

huangapple
  • 本文由 发表于 2023年6月22日 17:40:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76530535.html
匿名

发表评论

匿名网友

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

确定