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(",");
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(","));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With