How to Join a List of Strings or Object with a Colon in Java 8 Using Collectors.joining()

Learn How to Join a List of Strings or Object with a Colon in Java 8 Using Collectors.joining() (With Delimiter, Prefix, and Suffix Example)

  • Create a class named HelloCompany.
  • Store company name and address inside that class.
  • Create three company objects.
  • Add those objects to a list.
  • Convert the list into a stream.
  • Extract only company names using map().
  • Join all company names using Collectors.joining().
  • Add : between names, < at start, and > at end.
  • Print the final joined string.
				
					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) {
		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>

FAQ

Difference between map() and joining()

map()

  • Used to convert one type of data into another type.
  • Here, object → string

joining()

  • Used to combine multiple strings into one string.