开发者

Convert Set<Integer> to Set<String> in Java

Is there a simple way to convert Set<Integer> to Set<String> without iterating through t开发者_如何转开发he entire set?


No. The best way is a loop.

HashSet<String> strs = new HashSet<String>(ints.size());
for(Integer integer : ints) {
  strs.add(integer.toString());
}

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.

HashSet<String> strs = new HashSet<>(ints.size());
ints.forEach(i -> strs.add(i.toString()));

or, using Streams,

Set<String> strs = ints.stream().map(Integer::toString).collect(toSet());


use Java8 stream map and collect abilities:

 Set< String >  stringSet = 
   intSet.stream().map(e -> String.valueOf(e)).collect(Collectors.toSet());


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


You could use Commons Collections' TransformedSet or Guava's Collections2.transform(...)

In both cases, your functor would presumably simply call the Integer's toString().


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, 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.


Using Eclipse Collections with Java 8:

Set<String> strings = IntSets.mutable.with(1, 2, 3).collect(String::valueOf);

This doesn't require boxing the int values and Integer, but you can do that as well if required:

Set<String> strings = Sets.mutable.with(1, 2, 3).collect(String::valueOf);

Sets.mutable.with(1, 2, 3) will return a MutableSet<Integer>, unlike IntSets.mutable.with(1, 2, 3) which will return a MutableIntSet.

Note: I am a committer for Eclipse Collections.


private static <T> Set<T> toSet(Set<?> set) {
    Set<T> setOfType = new HashSet<>(set.size());
    set.forEach(ele -> {
        setOfType.add((T) ele);
    });
    return setOfType;
 }


Java 7 + Guava (presumably no way to switch to Java 8).

new HashSet<>(Collections2.transform(<your set of Integers>, Functions.toStringFunction()))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜