1

I want to get either empty list or list of strings from CSV. And I tried below approach:

String valueStr = "US,UK";
List<String> countryCodes = StringUtils.isBlank(valueStr)
                                    ? Collections.emptyList()
                                    : Arrays.stream(valueStr.split(DELIMITER))
                                            .map(String::trim)
                                            .collect(Collectors.toList());

How can I make it more concise without ternary operator, keeping it easy as well? This works fine. Just checking other approaches.

3
  • Is this just a 1-record csv document? Commented Aug 1, 2019 at 12:27
  • you mean single line? then, yes! Commented Aug 1, 2019 at 12:28
  • 2
    Try something like this : Optional.ofNullable(valueStr) .map(s->Arrays.stream(s.split(DELIMITER)) .map(String::trim) .collect(Collectors.toList())).orElse(Collections.emptyList()); Commented Aug 1, 2019 at 12:31

2 Answers 2

1
static Pattern p = Pattern.compile(DELIMITER);

public static List<String> getIt(String valueStr) {

    return Optional.ofNullable(valueStr)
                   .map(p::splitAsStream)
                   .map(x -> x.map(String::trim).collect(Collectors.toList()))
                   .orElse(Collections.emptyList());
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can filter:

List<String> countryCodes = Arrays.stream(
            StringUtils.trimToEmpty(valueStr).split(DELIMITER))
        .filter(v -> !v.trim().isEmpty())
        .collect(Collectors.toList());

The above returns an empty list when tested with a blank. It also excludes blank values (such as the last value from "UK,")

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.