Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 627
Krishna Hebbur Avatar asked Oct 27 '25 06:10

Krishna Hebbur


1 Answers

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());
like image 133
Nithin Avatar answered Oct 29 '25 21:10

Nithin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!