转换集<整数>设置<字符串>爪哇语字符串>整数>
有没有一种简单的方法可以将 Set
转换为 Set
而无需迭代整个集合?
Is there a simple way to convert Set<Integer>
to Set<String>
without iterating through the entire set?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
不,最好的方法是循环。
简单、相对快速、直接且富有表现力的东西可能是最好的。
(更新:)在 Java 8 中,如果您想隐藏循环,可以使用 lambda 表达式完成同样的操作。
或者,使用 Streams,
No. The best way is a loop.
Something simple and relatively quick that is straightforward and expressive is probably best.
(Update:) In Java 8, the same thing can be done with a lambda expression if you'd like to hide the loop.
or, using Streams,
使用Java8流映射和收集能力:
use Java8 stream map and collect abilities:
不可以。您必须格式化每个整数并将其添加到字符串集中。
No. You have to format each integer and add it to your string set.
如果您确实不想迭代整个集合,则可以使用装饰器
You can use a decorator if you really don't want to iterate through the entire set
您可以使用 Commons Collections 的 TransformedSet 或 Guava 的<一href="http://guava-libraries.googlecode.com/svn/tags/release09/javadoc/com/google/common/collect/Collections2.html#transform%28java.util.Collection,%20com.google.common。 base.Function%29" rel="nofollow">Collections2.transform(...)
在这两种情况下,您的函子可能会简单地调用整数的 toString()。
You could use Commons Collections' TransformedSet or Guava's Collections2.transform(...)
In both cases, your functor would presumably simply call the Integer's toString().
您可以自己实现
Set
并将所有调用重定向到原始集合,仅在需要时处理必要的转换。根据该组的使用方式,其性能可能会明显更好或明显更差。You could implement
Set<String>
yourself and redirect all calls to the original set taking care of the necessary conversions only when needed. Depending on how the set is used that might perform significantly better or significantly worse.AFAIK,你必须遍历集合;尤其是当涉及到不自然的转换时。即,如果您尝试从 Set-Timestamp- 转换为 Set-Date-;您可以使用 Java 泛型的某种组合来实现这一点(因为 Timestamp 可以转换为 Date)。但由于 Integer 无法转换为 String,因此您需要迭代。
AFAIK, you have to iterate through the collection; especially when there is a conversion involved that isn't natural. i.e. if you were trying to convert from Set-Timestamp- to Set-Date-; you could achieve that using some combination of Java Generics (since Timestamp can be cast to Date). But since Integer can't be cast to String, you will need to iterate.
在 Java 8 中使用 Eclipse Collections:
这不需要装箱 int 值和 Integer,但您可以如果需要,也可以这样做:
Sets.mutable.with(1, 2, 3)
将返回一个MutableSet
,与此不同IntSets.mutable.with(1, 2, 3)
它将返回一个MutableIntSet
。注意:我是 Eclipse Collections 的提交者。
Using Eclipse Collections with Java 8:
This doesn't require boxing the int values and Integer, but you can do that as well if required:
Sets.mutable.with(1, 2, 3)
will return aMutableSet<Integer>
, unlikeIntSets.mutable.with(1, 2, 3)
which will return aMutableIntSet
.Note: I am a committer for Eclipse Collections.
Java 7 + Guava(大概没办法切换到Java 8)。
Java 7 + Guava (presumably no way to switch to Java 8).