Prabu Prabu - 3 months ago 10
Java Question

Java Tree Map print value clarification

My question

while printing the map value i want to print which key having more than one values

Below are the details

static Map<Integer, Set<String>> myMap = new TreeMap<>();


Key value
1 a
b
c

2 d

3 e

4 f
g
h


based on the above
i want to print 1 and 4 only we need to omit 2 and 3

Printing

myMap.entrySet().forEach((e) -> {
System.out.println(e.getKey());
e.getValue().forEach((c) -> {
System.out.println(" " + c);
});
});

Answer

Is there a particular reason you're using streams for this? The standard imperative format is both easier to write and easier to read:

for (Entry<Integer, Set<String>> e : myMap.entrySet()) {
  if (e.getValue().size() > 1) {
    System.out.println(e.getKey());
    for (String s : e.getValue()) {
      System.out.println("    " + s);
    }
  }
}

Granted, it's a few more lines but terseness isn't necessarily a virtue. Clarity should be your primary concern.