[Java] Remove empty items in List

For Removing empty item in list, it can be be done directly. When using method removeIf(), it will throw UnSupportOperationException . It caused by collection items cannot be removed.

There has some tricks to remove list item. It can be done by using Java Stream to filter unwanted item out. In the demo it will use List<String> as example to remove null and blank item in list.

private List<String> removeEmptyItem(List<String> stringList) {
  return stringList.stream().filter(o->Objects.nonNull(o) && !o.trim().isBlank()).collect(Collectors.toList());
}

 

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.