The code below should give you what you want.
for (Map.Entry<Integer, List<String>> entry : contactList.entrySet()) {
List<String> values = entry.getValue();
StringBuilder builder = new StringBuilder(entry.getKey()).append(" - ");
// here I assume the values list is never null, and we pick at most the first 3 entries
builder.append("[")
for (int i = 0; i < Math.min(3, values.size()); i++) {
if (i > 0) builder.append(", ");
builder.append(values.get(i));
}
builder.append("[");
System.out.println(builder.toString());
}
What it does is, for each entry in the map:
- create a local variable with the value (a
List<String>
)
- create a
StringBuilder
for building the output on the entry
- iterate over the first 3 items (or less if the list is shorter) while building the output
- output the string in the builder
There's certainly a more elegant way to do it if you think about it, this is just a quick basic solution to your problem.