Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert set of integers to string in java

Tags:

java

string

set

I am trying to convert a set of integers to a single string in Java. How can I do that?

 Set<Integer> s = new HashSet<>();
        s.add(1);
        s.add(3);

        int n = s.size();
        String arr[] = new String[n];

        arr = s.toArray(arr);

        for (String x : arr )
            System.out.println(x);
like image 776
Teja Avatar asked Jun 04 '26 12:06

Teja


2 Answers

Use joining:

String result = s.stream().map(String::valueOf).collect(joining());

Without Stream:

List<String> intString = new ArrayList<>();
for (Integer i : s) {
   intString.add(String.valueOf(i));
} 

String result = String.join("", intString);

But be careful, if you want to print those numbers in input order (which is added first will be printed first), then you'll want a LinkedHashSet to remember that order:

Set<Integer s = new LinkedHashSet<>();
like image 104
Mạnh Quyết Nguyễn Avatar answered Jun 07 '26 10:06

Mạnh Quyết Nguyễn


With old-fashioned Java you can do it by using a StringBuilder:

StringBuilder builder = new StringBuilder();
for (Integer i : s) {
    builder.append(i);
}
String result = builder.toString();
like image 20
Thomas Fritsch Avatar answered Jun 07 '26 08:06

Thomas Fritsch