Java 8 Collectors.joining | join List of String using different delimiter

Here we are fetching Employee company name from using Collectors.joining method with List of String using different delimiter.

Here first we create EmployeeComapny name class with companyName and companyAddress String parameter.then we create EmployeeCompany argument constructor class and setter,getter method also.
Now we make one list of EmployeeCompany class.first we stream the list of data and from map we find out the company name.
Now use the Collectors.joining to pass the delimiter with prefix and suffix.
java.util.stream.Collectors.joining method is an overload of joining() method which takes delimiter,prefix and suffix as parameter, of the type CharSequence.

				
					// 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<EmployeeCompany> getList = Arrays.asList(new EmployeeCompany("TechMahindra", "Mumbai"),
				new EmployeeCompany("TCS", "Pune"), new EmployeeCompany("Wipro", "Bangalore"));
		String str = getList.stream().map(EmployeeCompany -> EmployeeCompany.getCompanyName())
				.collect(Collectors.joining(":", "[", "]"));
		System.out.println("Company name Joining:-- " + str);
	}

}
				
			

Output :-
Company name Joining:– [TechMahindra:TCS:Wipro]

Leave a Comment

Your email address will not be published. Required fields are marked *