Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove \n in every Arraylist item

I extract some Data into a Arraylist. And in every Item there are several line breaks (\n) that I want to get rid of afterwards.

I´ve tried to do this:

public List<String> MemberIDList() {

    // Getting the ArrayList
    idList =  listProjection.getIDListOfMembers();

    for (int i = 0; idList.size() > i; i++) {
       String item = idList.get(i);
        item.replaceAll("\n", "");
    }

    return idList;
}

If I print that out on the console, it still contains all the line breaks:

The ID ...... (not null) 
     145     
     145

Thanks

EDIT: I also want to filter unnecessary whitespace. Is ther a better option than running the answers down below twice. There are spaces --------------------- this huge.

idList.replaceAll(item -> item.replaceAll("\\s{2,}", "").trim());

I got it :D

like image 224
Trinity Avatar asked Dec 07 '22 11:12

Trinity


1 Answers

Change

item.replaceAll("\n", "");

to

idList.set(i,item.replaceAll("\n", ""));

item.replaceAll doesn't modify the state of the String referenced by item (which is impossible, since String is immutable). It returns a new String instead.

like image 196
Eran Avatar answered Dec 27 '22 05:12

Eran