Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there a simple way to convert Set<Integer> to Set<String> without iterating through the entire set?

like image 828
MatBanik Avatar asked May 10 '11 17:05

MatBanik


People also ask

Can we convert set to String in Java?

We can convert HashSet to String in Java using Apache Common's StringUtils class join() method as shown below in the example.


2 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());
like image 190
Cajunluke Avatar answered Sep 28 '22 11:09

Cajunluke


use Java8 stream map and collect abilities:

 Set< String >  stringSet = 
   intSet.stream().map(e -> String.valueOf(e)).collect(Collectors.toSet());
like image 39
doronk Avatar answered Sep 28 '22 12:09

doronk