Saturday 12 November 2022

Get the string representation of an Iterable

Write a function that takes an iterable and a delimeter as input and get the string representation of iterbale.

 

Signature

public static <T> String toString(final Iterable<T> iterable, final String delimiter, final boolean skipNull)

 

Find the below working application.


IterableToString.java
package com.sample.app.collections;

import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;

public class IterableToString {

	/**
	 * 
	 * @param <T>
	 * @param delimiter use comma (,), if it is null
	 * @param iterable
	 * @param skipNull, skip null values, it it is set to true, else add the string
	 *                  "null" for null values.
	 * 
	 * @return a string representation of the given iterable. Elements in the
	 *         iterable are separated by given delimeter.
	 */
	public static <T> String toString(final Iterable<T> iterable, final String delimiter, final boolean skipNull) {

		if (iterable == null) {
			return "";
		}

		String delimeterToUse = delimiter;

		if (delimiter == null) {
			delimeterToUse = ",";
		}

		final StringJoiner stringJoiner = new StringJoiner(delimeterToUse);

		for (T ele : iterable) {
			if (skipNull == true && ele == null) {
				continue;
			}

			if (ele == null) {
				stringJoiner.add("null");
			} else {
				stringJoiner.add(ele.toString());
			}

		}

		return stringJoiner.toString();

	}

	public static void main(String[] args) {
		List<Object> list = Arrays.asList(1, "krishna", null, 34, "Bangalore", true);

		String str1 = toString(list, "->", false);
		String str2 = toString(list, "->", true);

		System.out.println(str1);
		System.out.println(str2);

	}

}

 

Output

1->krishna->null->34->Bangalore->true
1->krishna->34->Bangalore->true

 

 

You may like

Interview Questions

Collection programs in Java

Array programs in Java

Get a map from array in Java

Convert an iterator to set in Java

Convert an enumeration to set in Java

Convert an enumeration to Iterable in Java

Convert an array to set in Java

No comments:

Post a Comment