Using Java 8 stream
You can try using stream groupingBy
feature to get the count
of each member type shown as below:
Logic:
Here, I have created a POJO class FamilyMember
with some attributes as given in the problem statement and created a list of FamilyMember and then by using stream
operation and using groupingBy
, grouped the data by memberType
and using Collectors.counting
getting the count of each memberType.
Suggestions:
As mentioned in the problem statement, the given input is in the form of List<Map<String, String>>
so instead of Map you can use a POJO class to hold the data for each member as shown in my implementation.
And moreover, how you are holding this kind of structure in the form of Map<String,String>
Code:
public class Test {
public static void main(String[] args) {
FamilyMember member1 = new FamilyMember("Sibling","Sibling name",
LocalDate.of(1990,12,12),"Male");
FamilyMember member2 = new FamilyMember("Sibling","Sibling name2",
LocalDate.of(1990,12,12),"Male");
FamilyMember member3 = new FamilyMember("Sibling","Sibling name3",
LocalDate.of(1990,12,12),"Male");
FamilyMember member4 = new FamilyMember("Child","Child name",
LocalDate.of(2010,12,12),"Male");
FamilyMember member5 = new FamilyMember("Child","Child name2",
LocalDate.of(2000,12,12),"Female");
FamilyMember member6 = new FamilyMember("Spouse","Spouse name",
LocalDate.of(1990,12,12),"Male");
List<FamilyMember> listOfFamilyMember = Arrays.asList(member1,member2,
member3,member4,member5,member6);
Map<String,Long> countMembers = listOfFamilyMember.stream()
.collect(Collectors.groupingBy(FamilyMember::getMemberType,
Collectors.counting()));
System.out.println(countMembers);
}
}
FamilyMember.java
public class FamilyMember {
private String memberType;
private String fullName;
private LocalDate dateOfBirth;
private String gender;
public FamilyMember(String memberType, String fullName,
LocalDate dateOfBirth, String gender) {
this.memberType = memberType;
this.fullName = fullName;
this.dateOfBirth = dateOfBirth;
this.gender = gender;
}
//getters and setters
}
Output:
{Spouse=1, Sibling=3, Child=2}