Skip to content

Instantly share code, notes, and snippets.

@osgix
Created May 10, 2017 07:52
Show Gist options
  • Save osgix/12368cd76234733833ed4f13d31a8059 to your computer and use it in GitHub Desktop.
Save osgix/12368cd76234733833ed4f13d31a8059 to your computer and use it in GitHub Desktop.
Printing key value pairs with given string format e.g. "%s is key of %s"
package com.example.collection;
import java.util.HashMap;
import java.util.Iterator;
public class PrintableHashMap<K, V> extends HashMap<K, V> {
private static final long serialVersionUID = 1L;
public String toString(String format) {
Iterator<Entry<K, V>> iterator = entrySet().iterator();
if (!iterator.hasNext()) {
return "{}";
}
StringBuilder sb = new StringBuilder();
sb.append("[");
while (iterator.hasNext()) {
Entry<K, V> entry = iterator.next();
K key = entry.getKey();
V value = entry.getValue();
String keyString = key == this ? "(this Map)" : key.toString();
String valueString = value == this ? "(this Map)" : value.toString();
String outputItem = String.format(format, keyString, valueString);
sb.append(outputItem);
if (!iterator.hasNext())
break;
sb.append(',').append(' ');
}
return sb.append(']').toString();
}
public static void main(String[] args) {
PrintableHashMap<String, String> map = new PrintableHashMap<>();
map.put("BJK", "Besiktas");
map.put("FB", "Fenerbahce");
map.put("GS", "Galatasaray");
System.out.println(map.toString("%s is abbr of %s"));
}
}
@osgix
Copy link
Author

osgix commented May 10, 2017

OUTPUT:
[BJK is abbr of Besiktas, FB is abbr of Fenerbahce, GS is abbr of Galatasaray]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment