此示例将使用给定的分隔符连接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方法,我们将使用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加入器,我们将用逗号分隔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);
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : http://www.leveluplunch.com/java/examples/convert-map-value-key-entries-to-string-with-separator/
内容来源于网络,如有侵权,请联系作者删除!