Reputation: 4362
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.
Upvotes: 1
Views: 569
Reputation: 45309
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,"
)
Upvotes: 1
Reputation: 120848
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());
}
Upvotes: 1