Printing the size of list items in map for each key

Viewed 111

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?

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

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