Sammy Sung
Sammy Sung

Reputation: 311

Unable to remove String from an Array

I am currently having a little problem removing a string from an array list. Code is as follows:

    String selectedCol = req.getParameter("col");
    if (selectedCol != null) {
        ArrayList < String > ar = new ArrayList < String > ();
        String removeColumn = layout.getColumn(selectedCol).getName();
        String layOut = "layout." + key + "." + layout.getName() + ".group";
        List < String > list = Arrays.asList(props.getProp(layOut, null).replace("[", "").replace("]", "").split(","));
        ar.addAll(list);
        ar.removeAll(Arrays.asList(removeColumn));
        props.putString(layOut, ar.toString().trim());
    }

so array "ar" populates the following:

[contact, created]

I thought it could be the list size which could be incorrect however it shows up with the correct size when I do ar.size()

The following variable:

removeColumn

is populated with "created".

I have tried the following:

ar.removeAll(Arrays.asList(removeColumn));

and

ar.remove(removeColumn);

which should result in:

[contact]

however using removeall or remove did not work. I am trying to achieve this without the need of looping through.

Help?

Upvotes: 0

Views: 119

Answers (2)

Deep
Deep

Reputation: 21

Your array elements may have some white spaces. Which is leading to mismatch. You can use “\s*,\s*” in split to get rid of those white spaces. Also use trim() to remove any leading or trailing spaces.

For Example:

    List < String > list = Arrays.asList(props.getProp(layOut, null).replace("[", "").replace("]", "").trim().split("\\s*,\\s*"));

Upvotes: 0

Boann
Boann

Reputation: 50041

You've generated the list from a string by splitting it on ",", but there are spaces between items in the string, so the two strings in your list are: "contact" and " created".

If you must parse a string in this way, change the split regex to ", ", or if you need it to be more tolerant to sloppy input, "\\s*,\\s*", allowing optional spaces before or after.

Upvotes: 4

Related Questions