xploreraj
xploreraj

Reputation: 4362

How can I convert csv to List with Java 8?

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

Answers (2)

ernest_k
ernest_k

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

Eugene
Eugene

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

Related Questions