0

I have a list of keys and values and I would like to print them so the values are left aligned with one another. So for instance if my map is: {(key9, val9), (key10, val10)} I want to print it as:

key9:  val9
key10: val10

My current solution is pretty ugly:

int maxKeyLength = findMaxKeyLength(myMap);
for (String key : myMap.keySet()) {
  int numSpaces = maxKeyLength - key.size() + 1;
  // TODO: use StringBuilder instead.
  String toPrint = key + ":";
  for (int i = 0;i < numSpaces;++i) {
    toPrint += " ";
  }
  toPrint += myMap.get(key);
  print(toPrint);
}

This works but is a bit ugly. My question is, is there any better way to do this?

Benjy Kessler
  • 7,356
  • 6
  • 41
  • 69

1 Answers1

0

You could try formatted strings, like so

for (String key : myMap.keySet()) {
   System.out.printf( "%-9s %-15s %n", key+":", myMap.get(key));
}

reference

depperm
  • 10,606
  • 4
  • 43
  • 67