Created
May 10, 2017 07:52
-
-
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"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OUTPUT:
[BJK is abbr of Besiktas, FB is abbr of Fenerbahce, GS is abbr of Galatasaray]