www.baeldung.com Open in urlscan Pro
2606:4700:3108::ac42:2b08  Public Scan

Submitted URL: https://t.dripemail2.com/c/eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJkZXRvdXIiLCJpc3MiOiJtb25vbGl0aCIsInN1YiI6ImRldG91cl9saW5rIiwia...
Effective URL: https://www.baeldung.com/guava-joiner-and-splitter-tutorial?__s=y8azgayhdvcyzudrce7c
Submission: On September 01 via manual from IN — Scanned from DE

Form analysis 0 forms found in the DOM

Text Content

WE VALUE YOUR PRIVACY

We and our partners store and/or access information on a device, such as cookies
and process personal data, such as unique identifiers and standard information
sent by a device for personalised ads and content, ad and content measurement,
and audience insights, as well as to develop and improve products. With your
permission we and our partners may use precise geolocation data and
identification through device scanning. You may click to consent to our and our
partners’ processing as described above. Alternatively you may access more
detailed information and change your preferences before consenting or to refuse
consenting. Please note that some processing of your personal data may not
require your consent, but you have a right to object to such processing. Your
preferences will apply to this website only. You can change your preferences at
any time by returning to this site or visit our privacy policy.
MORE OPTIONSAGREE
 * 
 * 
 * Start Here
 * Courses ▼▲
   
   
    * REST WITH SPRING
      
      The canonical reference for building a production grade API with Spring
   
   
    * LEARN SPRING SECURITY ▼▲
      
      THE unique Spring Security education if you’re working with Java today
      
      
       * LEARN SPRING SECURITY CORE
         
         Focus on the Core of Spring Security 5
      
      
       * LEARN SPRING SECURITY OAUTH
         
         Focus on the new OAuth2 stack in Spring Security 5
   
   
    * LEARN SPRING
      
      From no experience to actually building stuff
   
   
    * LEARN SPRING DATA JPA
      
      The full guide to persistence with Spring Data JPA

 * Guides ▼▲
   
   
    * PERSISTENCE
      
      The Persistence with Spring guides
   
   
    * REST
      
      The guides on building REST APIs with Spring
   
   
    * SECURITY
      
      The Spring Security guides

 * About ▼▲
   
   
    * FULL ARCHIVE
      
      The high level overview of all the articles on the site.
   
   
    * BAELDUNG EBOOKS
      
      Discover all of our eBooks
   
   
    * WRITE FOR BAELDUNG
      
      Become a writer on the site
   
   
    * ABOUT BAELDUNG
      
      About Baeldung.

 * 
 * 




GUAVA – JOIN AND SPLIT COLLECTIONS

Last modified: July 14, 2022

by Eugen Paraschiv
 * Guava
 * Java Collections

Generic Top


GET STARTED WITH SPRING 5 AND SPRING BOOT 2, THROUGH THE LEARN SPRING COURSE:

>> CHECK OUT THE COURSE



1. OVERVIEW



In this tutorial, we will learn how to use the Joiner and Splitter in the Guava
library. We'll convert collections into a String with the Joiner and we'll split
a String into a collection with the Splitter.


2. CONVERT LIST INTO STRING USING JOINER



Let's start with a simple example to join a List into a String using Joiner. In
the following example, we join a List of names into one String using the comma
“,” as a separator:

@Test
public void whenConvertListToString_thenConverted() {
    List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
    String result = Joiner.on(",").join(names);

    assertEquals(result, "John,Jane,Adam,Tom");
}


3. CONVERT MAP TO STRING USING JOINER



Next – let's see how to use Joiner to convert a Map to a String. In the
following example, we use withKeyValueSeparator() to join the key with its
value:

@Test
public void whenConvertMapToString_thenConverted() {
    Map<String, Integer> salary = Maps.newHashMap();
    salary.put("John", 1000);
    salary.put("Jane", 1500);
    String result = Joiner.on(" , ").withKeyValueSeparator(" = ")
                                    .join(salary);

    assertThat(result, containsString("John = 1000"));
    assertThat(result, containsString("Jane = 1500"));
}


4. JOIN NESTED COLLECTIONS



Now – let's see how to join nested collections into a String. In the following
example, we join the result of transforming each List to a String:

@Test
public void whenJoinNestedCollections_thenJoined() {
    List<ArrayList<String>> nested = Lists.newArrayList(
      Lists.newArrayList("apple", "banana", "orange"),
      Lists.newArrayList("cat", "dog", "bird"),
      Lists.newArrayList("John", "Jane", "Adam"));
    String result = Joiner.on(";").join(Iterables.transform(nested,
      new Function<List<String>, String>() {
          @Override
          public String apply(List<String> input) {
              return Joiner.on("-").join(input);
          }
      }));

    assertThat(result, containsString("apple-banana-orange"));
    assertThat(result, containsString("cat-dog-bird"));
    assertThat(result, containsString("John-Jane-Adam"));
}


5. HANDLE NULL VALUES WHILE USING JOINER



Now – let's see different ways to Handle Null Values While Using Joiner.



To skip null values while joining collection use skipNulls() as in the following
example:

@Test
public void whenConvertListToStringAndSkipNull_thenConverted() {
    List<String> names = Lists.newArrayList("John", null, "Jane", "Adam", "Tom");
    String result = Joiner.on(",").skipNulls().join(names);

    assertEquals(result, "John,Jane,Adam,Tom");
}

If you don't want to skip null values and want to replace them instead, use
useForNull() as in the following example:

@Test
public void whenUseForNull_thenUsed() {
    List<String> names = Lists.newArrayList("John", null, "Jane", "Adam", "Tom");
    String result = Joiner.on(",").useForNull("nameless").join(names);

    assertEquals(result, "John,nameless,Jane,Adam,Tom");
}

Note that useForNull() doesn't change the original list, it only affect the
output of the join.


6. CREATE LIST FROM STRING USING SPLITTER



Now – let's see how to split a String into a List. In the following example, we
use “-” separator to split the input String to List:

@Test
public void whenCreateListFromString_thenCreated() {
    String input = "apple - banana - orange";
    List<String> result = Splitter.on("-").trimResults()
                                          .splitToList(input);

    assertThat(result, contains("apple", "banana", "orange"));
}

Note that trimResults() removes the leading and trailing whitespace from the
resulting substrings.




7. CREATE MAP FROM STRING USING SPLITTER



Next – let's see how Create Map from String Using Splitter. In the following
example, we use withKeyValueSeparator() to split a String into a Map:

@Test
public void whenCreateMapFromString_thenCreated() {
    String input = "John=first,Adam=second";
    Map<String, String> result = Splitter.on(",")
                                         .withKeyValueSeparator("=")
                                         .split(input);

    assertEquals("first", result.get("John"));
    assertEquals("second", result.get("Adam"));
}


8. SPLIT STRING WITH MULTIPLE SEPARATORS



Now – let's see how to split a String with multiple separators. In the following
example, we use both “.” and “,” to split our String:

@Test
public void whenSplitStringOnMultipleSeparator_thenSplit() {
    String input = "apple.banana,,orange,,.";
    List<String> result = Splitter.onPattern("[.,]")
                                  .omitEmptyStrings()
                                  .splitToList(input);

    assertThat(result, contains("apple", "banana", "orange"));
}

Note that omitEmptyStrings() ignores empty strings and doesn't add them to the
resulting List.


9. SPLIT A STRING AT SPECIFIC LENGTH



Next – let's take a look on splitting a String at specific length. In the
following example, we split our String every 3 characters:

@Test
public void whenSplitStringOnSpecificLength_thenSplit() {
    String input = "Hello world";
    List<String> result = Splitter.fixedLength(3).splitToList(input);

    assertThat(result, contains("Hel", "lo ", "wor", "ld"));
}


10. LIMIT THE SPLIT RESULT



Finally – let's see how to Limit the Split Result. If you want the Splitter to
stop splitting after specific number of items – use limit() as in the following
example:



@Test
public void whenLimitSplitting_thenLimited() {
    String input = "a,b,c,d,e";
    List<String> result = Splitter.on(",")
                                  .limit(4)
                                  .splitToList(input);

    assertEquals(4, result.size());
    assertThat(result, contains("a", "b", "c", "d,e"));
}


11. CONCLUSION



In this tutorial we illustrated how to use both the Joiner and Splitter in Guava
to do a variety of transformations between collections and Strings.

The implementation of all these examples and code snippets can be found in my
Guava github project – this is an Eclipse based project, so it should be easy to
import and run as it is.

Generic bottom


GET STARTED WITH SPRING 5 AND SPRING BOOT 2, THROUGH THE LEARN SPRING COURSE:

>> CHECK OUT THE COURSE
Generic footer banner
Learning to build your API
with Spring?
Download the E-book
Comments are closed on this article!

Java sidebar banner
Building a REST API with Spring 5?
Download the E-book





COURSES

 * All Courses
 * All Bulk Courses
 * The Courses Platform

SERIES

 * Java “Back to Basics” Tutorial
 * Jackson JSON Tutorial
 * Apache HttpClient Tutorial
 * REST with Spring Tutorial
 * Spring Persistence Tutorial
 * Security with Spring
 * Spring Reactive Tutorials

ABOUT

 * About Baeldung
 * The Full Archive
 * Editors
 * Jobs
 * Our Partners
 * Partner with Baeldung

 * Terms of Service
 * Privacy Policy
 * Company Info
 * Contact