Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String split, filter and join in single line java 8

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(",");
like image 944
user1614862 Avatar asked Nov 07 '19 10:11

user1614862


1 Answers

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(","));
like image 90
Ravindra Ranwala Avatar answered Oct 19 '22 17:10

Ravindra Ranwala