In Java 8 Collectors.joining() method is used to combine elements of a stream into a single string. It is especially useful when you want to join a list of strings using a delimiter, along with optional prefix and suffix values.
Collectors.joining():
Collectors.joining() is a method in the java.util.stream.Collectors class. It is used to concatenate stream elements into a single string.
In this example, we fetch employee company names and join them using a delimiter, prefix, and suffix.
- First, we create a list of EmployeeCompany objects.
- Using stream(), we process the list .
- The map() method extracts company names.
- Finally, Collectors.joining() joins the names:
- : → delimiter
- [ → prefix
- ] → suffix
// Model class:-
class EmployeeCompany {
private String companyName;
private String companyAddress;
public EmployeeCompany(String companyName, String companyAddress) {
super();
this.companyName = companyName;
this.companyAddress = companyAddress;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getCompanyAddress() {
return companyAddress;
}
public void setCompanyAddress(String companyAddress) {
this.companyAddress = companyAddress;
}
}
// Main class:-
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CompanyListJoin {
public static void main(String[] args) {
List getList = Arrays.asList(
new EmployeeCompany("TechMahindra", "Mumbai"),
new EmployeeCompany("TCS", "Pune"), new EmployeeCompany("Wipro", "Bangalore"));
String str = getList.stream().map(employee
-> employee.getCompanyName())
.collect(Collectors.joining(":", "[", "]"));
System.out.println("Company name Joining:-- " + str);
}
}
Output :-
Company name Joining:– [TechMahindra:TCS:Wipro]