使用Java和Guava将Map转换为字符串

x33g5p2x  于4个月前 转载在 其他  
字(1.7k)|赞(0)|评价(0)|浏览(355)

此示例将使用给定的分隔符连接Map的键和值。在setup方法中,我们将使用一系列书籍初始化Map。键将代表标题,而值将是书的价格。这些书是从Amazon's Great American Eats: Cookbooks Out of the Pacific Northwest中取出的。

设置

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);
}

Java

使用直接的java方法,我们将使用StringBuffer连接Map中的每个条目,这些条目由逗号和键值分隔符分隔。

@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());

}

谷歌Guava

使用Guava加入器,我们将用逗号分隔Map中的每个条目。通过指定键值分隔符,Map键和值将与“cost”连接,生成键+值+分隔符组合。请注意,此示例中的底层joiner是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);

}

相关文章

微信公众号

最新文章

更多