将 Set转换为最简洁的方法到列表
例如,我目前正在这样做:
Set<String> setOfTopicAuthors = ....
List<String> list = Arrays.asList(
setOfTopicAuthors.toArray( new String[0] ) );
你能打败这个吗?
For example, I am currently doing this:
Set<String> setOfTopicAuthors = ....
List<String> list = Arrays.asList(
setOfTopicAuthors.toArray( new String[0] ) );
Can you beat this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
考虑到我们有
Set; stringSet
我们可以使用以下内容:Plain Java
Guava
Apache Commons
Java 10(不可修改列表)
Java 8(可修改列表)
根据 doc 方法
toList()
因此,如果我们需要一个特定的实现,例如
ArrayList
,我们可以通过以下方式获得它:Java 8(不可修改列表)
我们可以使用
Collections::unmodifyingList
方法并包装列表在前面的示例中返回。我们还可以将自己的自定义方法编写为:然后将其用作:
另一种可能性是使用
collectingAndThen
方法,该方法允许在返回结果之前完成一些最终转换:一个指向注意是,方法
Collections::unmodifyingList
返回指定列表的不可修改视图,按照doc。不可修改的视图集合是不可修改的集合,也是支持集合的视图。请注意,对支持集合的更改可能仍然是可能的,并且如果发生,它们可以通过不可修改的视图可见。但是收集器方法Collectors.unmodifyingList
返回Java 10中真正不可变的列表。Considering that we have
Set<String> stringSet
we can use following:Plain Java
Guava
Apache Commons
Java 10 (Unmodifiable List)
Java 8 (Modifiable Lists)
As per the doc for the method
toList()
So if we need a specific implementation e.g.
ArrayList
we can get it this way:Java 8 (Unmodifiable Lists)
We can make use of
Collections::unmodifiableList
method and wrap the list returned in previous examples. We can also write our own custom method as:And then use it as:
Another possibility is to make use of
collectingAndThen
method which allows some final transformation to be done before returning result:One point to note is that the method
Collections::unmodifiableList
returns an unmodifiable view of the specified list, as per doc. An unmodifiable view collection is a collection that is unmodifiable and is also a view onto a backing collection. Note that changes to the backing collection might still be possible, and if they occur, they are visible through the unmodifiable view. But the collector methodCollectors.unmodifiableList
returns truly immutable list in Java 10.尝试一下 Set:
尝试一下 地图:
Try this for Set:
Try this for Map:
如果您使用的是 Guava,则可以从 列表 类:
If you are using Guava, you statically import
newArrayList
method from Lists class:不太确定您通过代码上下文到底在做什么,但是...
为什么要创建
listOfTopicAuthors
变量呢?“....”代表您的套装如何发挥作用,无论它是新的还是来自其他位置。
not really sure what you're doing exactly via the context of your code but...
why make the
listOfTopicAuthors
variable at all?the "...." represents however your set came into play, whether it's new or came from another location.