Is there a simple way to convert Set<Integer> to Set<String> without iterating through the entire set?
10 Answers
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());
11 Comments
toString instead of stringValue ;)Integer's .intValue().NullPointerException in the call to toString() as a Set<T> can contain a null value.""+integer ;)You can use a decorator if you really don't want to iterate through the entire set
4 Comments
You could use Commons Collections' TransformedSet or Guava's Collections2.transform(...)
In both cases, your functor would presumably simply call the Integer's toString().
Comments
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.
1 Comment
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.
Lists: stackoverflow.com/questions/18524/…