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?
Printing All Keys and Values From the HashMapforEach(key -> System. out. println(key));
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With