Prabu
Prabu

Reputation: 3728

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);
                });
            });

Upvotes: 3

Views: 442

Answers (2)

dimo414
dimo414

Reputation: 48814

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.

Upvotes: 2

Akash Thakare
Akash Thakare

Reputation: 22972

You can apply filter

myMap.entrySet().stream().filter(entry -> entry.getValue().size() > 1).forEach...

For example,

public class Test {

    public static void main(String[] args) {
        Map<Integer, Set<String>> myMap = new TreeMap<>();
        Set<String> set1 = new HashSet<>();
        Set<String> set2 = new HashSet<>();
        Set<String> set3 = new HashSet<>();

        set1.add("1");
        set1.add("2");
        set1.add("3");

        set2.add("2");

        set3.add("1");
        set3.add("2");

        myMap.put(1, set1);//3 Elements
        myMap.put(2, set2);//1 Element
        myMap.put(3, set3);//2 Elements

        myMap.entrySet().stream()
             .filter(entry -> entry.getValue() != null)
             .filter(entry -> entry.getValue().size() > 1)
             .forEach(System.out::println);
    }

}

Output

1=[1, 2, 3]
3=[1, 2]

Upvotes: 4

Related Questions