Searching...
Saturday, 15 March 2014

Joining Iterable values using Guava Joiner

08:09

Joiner is an object which joins pieces of text which is from Iterable like ArrayList or Map. Here is one simple example to Joins ArrayList and Map values using Guava Joiner.

1. Create a Maven project add Guava dependency

  <dependency>
	<groupId>com.google.guava</groupId>
	<artifactId>guava</artifactId>
	<version>r09</version>
</dependency>

2. Create a Main Program to Join values (JoinerExample.java)

package com.pretech;
import java.util.List;
import java.util.Map;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
public class JoinerExample {
	public static void main(String[] args) {
		// ArrayList Joining and skipping null
		final List<String> days = Lists.newArrayList("sunday", "monday",
				"tuesday", null);
		System.out.println(Joiner.on("\t ").skipNulls().join(days));
		// Map Joining
		final Map<String, String> personDetails = ImmutableMap.of("Name",
				"vinod", "Location", "Bangalore");
		System.out.println(Joiner.on("\t").withKeyValueSeparator(": ")
				.join(personDetails));
	}
}

3. Output



sunday     monday     tuesday
Name: vinod    Location: Bangalore


0 comments: