String split, filter and join in single line java 8

use*_*862 6 java string java-8 java-stream

I have string which I would like to split by comma and check for a specific word in each one and then trim and then join it to create new string

Input:

"UC_Admin, Internal, UC_Reg, US_Admin"
Run Code Online (Sandbox Code Playgroud)

Desired Output:

 "UC_Admin,UC_Reg"
Run Code Online (Sandbox Code Playgroud)

What I tried is:

Arrays.stream("UC_Admin,Internal,UC_Reg,US_Admin".split(","))
      .filter(role -> role.contains("UC").join(",");
Run Code Online (Sandbox Code Playgroud)

Rav*_*ala 8

You have to use Collectors.joining(",") here. Also note that for the trim operation you can merely use the map operator.

String result = Arrays.stream("UC_Admin,Internal,UC_Reg,US_Admin".split(","))
    .filter(role -> role.contains("UC"))
    .map(String::trim).collect(Collectors.joining(","));
Run Code Online (Sandbox Code Playgroud)

A much better approach is given below. This should outperform the former solution for a large data set. However, I have not conducted any benchmark to prove that.

private static final Pattern COMMA = Pattern.compile(",");

String result = COMMA.splitAsStream("UC_Admin,Internal,UC_Reg,US_Admin")
    .filter(role -> role.contains("UC"))
    .map(String::trim)
    .collect(Collectors.joining(","));
Run Code Online (Sandbox Code Playgroud)