Convert map to string

This example will join a map's key and value with a given separator. In the set up method we will initialize a map with a series of books. The keys will represent the title while the value will be the price of the book. The books were pulled from from Amazon's Great American Eats: Cookbooks Out of the Pacific Northwest.

Setup

private Map<String, Double> bookAndPrice = new HashMap<>();

@Before
public void setUp() {
    bookAndPrice.put("Delancey: A Man, a Woman, a Restaurant, a Marriage",
            18.63);
    bookAndPrice.put("Whole-Grain Mornings: New Breakfast Recipes to Span",
            13.92);
    bookAndPrice.put("Greg Atkinsons In Season: Culinary Adventures of a",
            15.57);
}

Straight up Java

Using a straight up java approach we will use a StringBuffer to concatenate each entry within the map separated by a comma and a key value separator.

@Test
public void convert_map_to_string_java() {

    String separator = ", ";
    String keyValueSeparator = " cost ";

    StringBuffer buffer = new StringBuffer();

    Iterator<Entry<String, Double>> entryIterator = bookAndPrice.entrySet()
            .iterator();

    while (entryIterator.hasNext()) {

        Entry<String, Double> entry = entryIterator.next();

        buffer.append(entry.getKey());
        buffer.append(keyValueSeparator);
        buffer.append(entry.getValue());

        if (entryIterator.hasNext()) {
            buffer.append(separator);
        }
    }
    assertEquals(
            "Delancey: A Man, a Woman, a Restaurant, a Marriage cost 18.63, "
                    + "Whole-Grain Mornings: New Breakfast Recipes to Span cost 13.92, "
                    + "Greg Atkinsons In Season: Culinary Adventures of a cost 15.57",
            buffer.toString());

}

Google Guava

Using guava joiner we will seperate each entry within a map with a comma. By specifying a key value separator the map key and value will be joined with "cost" producing a key + value + separator combination. Note, the underlying joiner in this instance is a MapJoiner

@Test
public void convert_map_to_string_guava() {

    String mapJoined = Joiner.on(", ").withKeyValueSeparator(" cost ")
            .join(bookAndPrice);

    assertEquals(
            "Delancey: A Man, a Woman, a Restaurant, a Marriage cost 18.63, "
                    + "Whole-Grain Mornings: New Breakfast Recipes to Span cost 13.92, "
                    + "Greg Atkinsons In Season: Culinary Adventures of a cost 15.57",
            mapJoined);

}