3

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]

1
  • 2
    Use the filter method to only return those elements that fit your needs Commented Jan 20, 2020 at 7:47

3 Answers 3

7

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());
Sign up to request clarification or add additional context in comments.

7 Comments

Good answer. Only one doubt if physician.getStateDetails().getStateCode() have a space.
Sudhir, use StringUtils.IsNotEmpty
@SudhirOjha in that case, you have to change the filter Predicate to something like s -> !s.trim().isEmpty()
No need to trim() in .map(....) or remove it from filter(...)
Or filter(String::isBlank) from Java11
|
2

You should trim the strings first, after that filter by isEmpty and collect.

Comments

0

I will do:

List<String> stateCodes =
stateList.stream()
         .map(state-> physician.getStateDetails().getStateCode())
         .filter(s -> !s.trim().isEmpty())
         .collect(Collectors.toList());
  • I add a filter on data and remove the empty data - used trim only in predicate.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.