简体   繁体   中英

Splitting comma separated string values when streaming in java 8

I have a String field called userId that has comma separated values like String user = "123","456" I want to split it. I have written something like this

List<String> idList= employeeList.stream()
    .map(UserDto::getUserId)
    .filter(Objects::nonNull)
    .map(String::toUpperCase)
    .distinct()
    .collect(Collectors.toList());

This UserDto::getUserId contains the comma separated values. Is it possible to split when streaming in the above logic.

Thanks

I think this should work

List<String> idList= employeeList.stream()
    .map(UserDto::getUserId)
    .filter(Objects::nonNull)
    .map(String::toUpperCase)
    .flatMap(s -> Arrays.stream(s.split(",")))//create a stream of split values
    .distinct()
    .collect(Collectors.toList());

Just use the split(...) method of String and flatMap(...) to go from the stream of arrays to a stream of the elements inside the arrays:

List<String> idList = employeeList.stream()
                .map(UserDto::getUserId)
                .filter(Objects::nonNull)
                .map(userId -> userId.split(",")) //get from the comma separated list to an array of elements
                .flatMap(Arrays::stream) //transform the stream of arrays to a stream of the elements inside the arrays
                .map(String::toUpperCase)
                .distinct()
                .collect(Collectors.toList());

It is possible to split it by using and it's like

.map(ids -> ids.toUpperCase().split(","))

But If you wanna create new list with IDs you can just apply for
1st Solution

List<String> splitted = new ArrayList<>();
list.stream().filter(Objects::nonNull).forEach(it -> splitted.addAll(Arrays.asList(it.toUpperCase().split(","))));

2nd Solution

list.stream().filter(Objects::nonNull).map(it -> Arrays.asList(it.toUpperCase().split(","))).flatMap(Collection::stream).collect(Collectors.toList());

Here it is:

employeeList.stream()
.map(UserDto::getUserId)
.filter(Objects::nonNull)
.map(ids -> ids.split(","))
.flatMap(Arrays::stream)
.map(String::toUpperCase)
.distinct()
.collect(Collectors.toList());

Take a look at how FlatMap works ;)

if you need to perform the splitting quite often and performance is of the essence and/or split by a more complex rule, like split by , and remove white spaces using the Pattern class should be considered:

Pattern splitter = Pattern.compile("\\s*,\\s*");
List<String> idList= employeeList.stream()
        .map(UserDto::getUserId)
        .filter(Objects::nonNull)
        .map(String::toUpperCase)
        .flatMap(s -> splitter.splitAsStream(s))
        .distinct()
        .collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM