If I have following map:
NavigableMap<Integer,String> nmap =
new TreeMap<Integer,String>();
nmap.put(3, "Three");
nmap.put(1, "One");
nmap.put(4, "Four");
nmap.put(5, "Five");
nmap.put(7, "Seven");
nmap.put(10, "Ten");
System.out.println(nmap);
// {1=One, 3=Three, 4=Four, 5=Five, 7=Seven, 10=Ten}
Is there a mechanism, that can allow me to print this, printing by index value, if index is smaller more than 1 from the following index print -(dash):
One,-,开发者_StackOverflow中文版Three,Four,Five,-,Six,Seven,-,-,Ten
How would I write function for this?
I don't have to print whole map to string I meant for each key/value pair
Here's a generalized solution, that also does the concatenation. My generics knownledge is a bit dodgy, so don't be surprised by the odd mistake:
static <V> List<V> NMapToList(NavigableMap<Integer,V> nmap, V emptyEntryValue)
{
Integer next = null;
List<V> list = new ArrayList<V>();
for(NavigableMap.Entry<Integer, V> e : nmap.entrySet())
{
Integer current = e.getKey();
if(next != null)
for(int i = next; i < current; i++)
list.add(emptyEntryValue);
list.add(e.getValue());
next = current + 1;
}
return list;
}
static String listToString(List<?> l, String separator)
{
StringBuilder sb = new StringBuilder("(");
String sep = "";
for (Object object : l)
{
sb.append(sep).append(object.toString());
sep = separator;
}
return sb.append(")").toString();
}
String s = listToString(NMapToList(nmap,'-'),',');
Untested, but should work:
public String myToString(final NavigableMap<Integer, String> nmap) {
StringBuilder sb = new StringBuilder();
Integer lastKey = null;
for (Map.Entry<Integer, String> entry : nmap.entrySet()) {
Integer key = entry.getKey();
if (lastKey != null) {
for (int i=(lastKey+1); i<key; i++) {
sb.append(",-");
}
}
if (sb.length() != 0) {
sb.append(",");
}
sb.append(entry.getValue());
lastKey = key;
}
return sb.toString();
}
You would have to create a new subclass of TreeMap and override the toString method.
You should use NavigableSet<K> navigableKeySet()
method of the NavigableMap, which returns a NavigableSet view of the keys contained in this map. The set's iterator returns the keys in ascending order. Then iterate on the Set and get the values from the NavigableMap.
Edit:
To use this System.out.println(nmap);
you should subclass from NavigableMap and override the toString()
method, using the steps I wrote earlier.
精彩评论