Wednesday 3 May 2023

Join the collection elements by a separator using streams

Below snippet join the collection elements by a delimiter using streams.

public static String join(final Collection<?> collection, final String delimiter) {
	if (collection == null) {
		return "";
	}

	Collector<CharSequence, ?, String> collector = Collectors.joining();

	if (delimiter != null) {
		collector = Collectors.joining(delimiter);
	}

	return collection.stream().map(String::valueOf).collect(collector);
}

 

‘Stream#map’ method is used to convert each element of the collection to its string representation, and the joining method of the Collectors class concatenates the strings using the specified delimiter.

 

Find the below working application.

 

CollectionElementsJoinDemo.java

package com.sample.app.collections;

import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collector;
import java.util.stream.Collectors;

public class CollectionElementsJoinDemo {

	public static String join(final Collection<?> collection, final String delimiter) {
		if (collection == null) {
			return "";
		}

		Collector<CharSequence, ?, String> collector = Collectors.joining();

		if (delimiter != null) {
			collector = Collectors.joining(delimiter);
		}

		return collection.stream().map(String::valueOf).collect(collector);
	}

	public static void main(String[] args) {
		Collection<String> data = Arrays.asList("India", "China", "Sri Lanka", "Nepal");

		String result1 = join(data, ",");
		String result2 = join(data, "->");
		String result3 = join(data, ";");

		System.out.println("result1 : " + result1);
		System.out.println("result2 : " + result2);
		System.out.println("result3 : " + result3);

	}

}

 

Output

result1 : India,China,Sri Lanka,Nepal
result2 : India->China->Sri Lanka->Nepal
result3 : India;China;Sri Lanka;Nepal

 

 

 

You may like

Interview Questions

Collection programs in Java

Array programs in Java

Convert an Iterable to List in Java

Convert an Iterable to a Set in Java

Get the last element from a collection in Java

Implement stack data structure using List

Get a composite unmodifiable array list from two arrays

No comments:

Post a Comment