Pegah.A
Pegah.A

Reputation: 85

Using toString() for set

I am using a set in my code which includes some integers in it. Somewhere in my code in need to have these numbers as a String so that a function could operate on them. (The function is permutation which gets a String as the input parameter.)

When my set is something like:

Set<Integer> U= new TreeSet<Integer>();
U.addAll(Arrays.asList(1,2,3,4,5,6,7,8,9));

I need a string with the length of 9 which has these nine numbers in it. But by using

String str=U.toString();

str would be [1, 2, 3, 4, 5, 6, 7, 8, 9] with the length of 27.

Is there anyway to store only the numbers into the string without the [ and , and spaces?

Upvotes: 1

Views: 184

Answers (6)

arshajii
arshajii

Reputation: 129547

You can try this:

Set<Integer> U = new TreeSet<Integer>();
U.addAll(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));

StringBuilder sb = new StringBuilder(U.size());
for (int a : U)
    sb.append(a);

System.out.println(sb);
123456789

Java 8 approach:

Iterable<String> iter = U.stream().map(Object::toString)::iterator;
System.out.println(String.join("", iter));
123456789

Upvotes: 0

Shishir Kumar
Shishir Kumar

Reputation: 8201

Simple use:

System.out.println(Arrays.toString(U.toArray()));

Upvotes: 0

Mureinik
Mureinik

Reputation: 312086

You'll need to implement it on your own:

public static String setToString(Set<Integer> set) {
    StringBuilder sb = new StringBuilder();
    for (Integer i : set) {
        sb.append(i);
    }
    return sb.toString();
}

Upvotes: 1

Christian Tapia
Christian Tapia

Reputation: 34176

One way would be creating your own method.You can loop through the Set, and use a StringBuilder to construct the String:

public String myToString() {
    StringBuilder sb = new StringBuilder();

    for (Integer i : U) {
        sb.append(i);
    }

    return sb.toString();
}

Another way would be overriding the toString() method. The implementation will be similar as the one above:

@Override
public String toString() {
    // ...
}

Upvotes: 1

Roberto Anić Banić
Roberto Anić Banić

Reputation: 1421

@Override the toString in your extension class. A simple for loop should do it

Upvotes: 1

Thomas
Thomas

Reputation: 1420

Create a subclass of TreeSet and override the toString() method as you want !

Upvotes: 1

Related Questions