String split, filter and join in single line java 8

user1614862 :

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"

Desired Output:

 "UC_Admin,UC_Reg"

What I tried is:

Arrays.stream("UC_Admin,Internal,UC_Reg,US_Admin".split(","))
      .filter(role -> role.contains("UC").join(",");
Ravindra Ranwala :

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(","));

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(","));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=321843&siteId=1