Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing the size of list items in map for each key

I have java POJO User which contains firstName of the user. There is a map which contains the list of users mapped against the school name. Something like the below

class User{
 String name;
}

class UserMap{
 Map<String,List<User> userMapOfSchool;

public String toString(){
 //return "schoolName has noOfStudents" for each key in the map
}
}

As mentioned above in the toString() method, I wanted to print the list school name and the number of students in the school. How can I do that in Java 8?

like image 402
Apps Avatar asked Sep 08 '18 13:09

Apps


People also ask

Which method is used to print all keys of HashMap?

Printing All Keys and Values From the HashMapforEach(key -> System. out. println(key));

How do I print an element in a HashMap?

Print HashMap using Consumer with entrySet() To use Consumer functional interface, you have to use the entrySet() method, which returns a Set containing the same type of key-value elements. Since the Set is a Collection class that implements Iterable , use the forEach() method to print out the elements of the HashMap.


2 Answers

I have java POJO User which contains firstName of the user.

It is not required for your requirement as you don't want to display any information of the users...

You can stream the map and collect it with the joining() collector :

class UserMap{
  Map<String,List<User> userMapOfSchool;

  @Override
  public String toString(){
   return
   userMapOfSchool.entrySet()
                  .stream()
                  .map(e -> e.getKey() + " has " + e.getValue().size() + " students")
                  .collect(joining("\n"));
  }
}
like image 59
davidxxx Avatar answered Oct 16 '22 07:10

davidxxx


If you're looking to iterate over the complete entrySet, this might be of use

public String toString() {
   StringBuilder userMap = new StringBuilder();
   userMapOfSchool.forEach((k, v) ->
                userMap.append(k).append(" school has ").append(v.size()).append("noOfStudents."));
   return userMap.toString(); 
}
like image 22
Naman Avatar answered Oct 16 '22 08:10

Naman