Is there a simple way to convert Set<Integer>
to Set<String>
without iterating through the entire set?
We can convert HashSet to String in Java using Apache Common's StringUtils class join() method as shown below in the example.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With