How to join List Sring class with colon from java 8?

The joining() method of Collectors Class, in Java, is used to join various elements of a character or string array into a single string object.If you want to join a Collection of Strings you can use the String.join() method.
With Java 8 you can do this without any third party library.If you have a Collection with another type than String you can use the Stream API with Collectors.joining
here we created one model class and pass this data to list.then we stream this list data to map and add colon with Collectors.joining method.

				
					import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

class HelloCompany {

	private String companyName;
	private String companyAddress;

	public HelloCompany(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;
	}

}

public class CompanyListJoin {
	public static void main(String[] args) {
		List<HelloCompany> getList = Arrays.asList(new HelloCompany("Reliance", "Mumbai"),
				new HelloCompany("TATA", "Pune"), new HelloCompany("Infosys", "Bangalore"));
		String str = getList.stream().map(HelloCompany -> HelloCompany.getCompanyName())
				.collect(Collectors.joining(":", "<", ">"));
		System.out.println("Company name Joining-- " + str);
	}
}

				
			

Output :-
Company name Joining- <Reliance:TATA:Infosys>

Leave a Comment

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