Ghadeer
Ghadeer

Reputation: 638

remove any digit from a set in Java

I have a set in Java looks like

[0.99998945, line10Rule:14013, noOfCommits:0]

and, I want to remove all digital numbers and colon ':' from its element to get

[line10Rule, noOfCommits]

What is the best way to do that?

Upvotes: 0

Views: 206

Answers (3)

GameDroids
GameDroids

Reputation: 5662

Now corrected:

String[] array = new String[set.size()];   // create a String array of the same size as the set
set.toArray(array);                        // copy the sets content into the array
set.clear();                               // clear the set

for (String string : array) {              // iterate through the array
    set.add(string.replaceAll("[0-9]*$", ""));   // remove the digits and put the resulting String back into the set    
}

@jlordo: thanks for pointing it out. I forgot, that the iterator works on a copy of the String. This may not be elegant (iterating through so many loops etc) but it works :D

regards Christoph

Upvotes: 2

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136002

Try this

    List<String> list = new ArrayList<String>(Arrays.asList("0.99998945", "line10Rule:14013", "noOfCommits:0"));
    ListIterator<String> i = list.listIterator();
    while(i.hasNext()) {
        String s = i.next();
        int p = s.indexOf(':');
        if (p > 0) {
            i.set(s.substring(0, p));
        } else {
            i.remove();
        }
    }
    System.out.println(list);

output

[line10Rule, noOfCommits]

Upvotes: 0

ignis
ignis

Reputation: 8852

No way, you will have to recreate the set item by item. To replace numbers with "", consider String.replace().

Upvotes: 0

Related Questions