Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove space from a list object while iterating using Java 8

This is my code , which is returning spaces along with some valid strings. But, my requirement is to invalidate space and collect only strings

List<String> stateCodes = stateList.stream()
                                    .map(state-> physician.getStateDetails().getStateCode())
                                    .collect(Collectors.toList());

When I print stateCodes, it returns

[ ,  , 197, 148,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ,  ]

Here I require only [197,148]

like image 253
Syed Avatar asked Sep 08 '26 08:09

Syed


1 Answers

Filter out the empty values. I'm not sure if those are empty Strings in your output. If they are, you can filter them out with:

List<String> stateCodes =
    stateList.stream()
             .map(state-> physician.getStateDetails().getStateCode())
             .filter(s -> !s.isEmpty())
             .collect(Collectors.toList());

Note: you can add trim() (to either the map or filter steps) to filter out Strings which contain only white spaces:

List<String> stateCodes =
    stateList.stream()
             .map(state-> physician.getStateDetails().getStateCode().trim())
             .filter(s -> !s.isEmpty())
             .collect(Collectors.toList());
like image 139
Eran Avatar answered Sep 09 '26 20:09

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!