0

I want to remove all empty element.. I use code below this, but did not working..

sejarahToken.removeAll(Collections.singleton(""));
    sejarahToken.removeAll(Arrays.asList(""));
    for (String st : sejarahToken) {
        writingFile(st);
    }

same as using this code:

 sejarahToken.removeAll(Collections.singleton(null));
 sejarahToken.removeAll(Arrays.asList(null,""));

Here's output the sejarahToken arraylist on txt file.. there are still empty values:

Leonardo
da
Vinci
dari
Italia
dan
Otto
Lilienthal
dari
Jerman
telah
mendahuluinya


Tetapi
ternyata
jauh
sebelumnya
semua
sudah
didahului
oleh
seorang
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
Lita
  • 175
  • 1
  • 2
  • 11
  • Perhaps you have entries which are just whitespace? It doesn't help that we don't know what `writingFile` looks like. Have you tried debugging through the code to see what the list looks like after the call to `removeAll`? – Jon Skeet Mar 31 '15 at 16:28
  • thank you.. i just realize.. all because of whitespace. thats why i can't remove using blankspace or null – Lita Mar 31 '15 at 17:33
  • I just knew.. I'm very glad you're giving me a warning and fix the question. I will remember that. – Lita Apr 06 '15 at 23:38

2 Answers2

2

You can use the following code snippet to remove if there are empty strings or strings with whitespaces.

final Iterator<String> iterator = sejarahToken.iterator();

while (iterator.hasNext()) {
  final String e = iterator.next();

  if (e == null || e.trim().isEmpty())
    iterator.remove();
}
Kennedy Oliveira
  • 2,141
  • 2
  • 20
  • 25
1

Use this

al.removeAll(Arrays.asList(null,""));

This will remove all elements that are null or equals to "" in your List.

Fahim
  • 12,198
  • 5
  • 39
  • 57