you can watch here for a very good guide
Anyway, i hope it helps you (maybe a little bit).
Main-Class
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class mainMethod {
public static void main(String[] args) {
List<Person> persons = new ArrayList<>();
persons.add(new Person(1, 1, 1));
persons.add(new Person(2, 2, 0));
persons.add(new Person(3, 1, 1));
persons.add(new Person(4, 11, 0));
persons.add(new Person(5, 20, 1));
persons.add(new Person(6, 20, 1));
persons.add(new Person(7, 2, 0));
persons.add(new Person(8, 20, 0));
persons.add(new Person(9, 11, 0));
persons.add(new Person(10, 20, 1));
TempObjectMapper tempObjectMapper = new TempObjectMapper(persons.stream()
.collect(Collectors.groupingBy(Person::getAge, Collectors.groupingBy(Person::getGender))));
List<TempObject> tempObjects = tempObjectMapper.getObjects();
System.out.println(tempObjects.toString());
}
}
TempObjectMapper
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class TempObjectMapper {
private Map<Integer, Map<Integer, List<Person>>> map;
public TempObjectMapper(Map<Integer, Map<Integer, List<Person>>> collect) {
this.map = collect;
}
public List<TempObject> getObjects() {
List<TempObject> list = new ArrayList<TempObject>();
this.map.forEach((key, value) -> {
int age = key;
Map<Integer,List<Person>> map1 = value;
map1.forEach((key1, value1) -> {
int gender = key1;
List<Person> person = value1;
list.add(new TempObject(age, gender, person));
});
});
return list;
}
}
TempObject
import java.util.List;
public class TempObject {
private int age;
private int gender;
private List<Person> persons;
public TempObject(int age, int gender, List<Person> persons) {
this.age = age;
this.gender = gender;
this.persons = persons;
}
@Override
public String toString() {
return String.format("TempObject: [%s,%s,%s]" , this.age, this.gender, this.persons.toString());
}
}
Person
public class Person {
private int personId;
private int age;
private int gender; //0 for male and 1 for female
public Person(int id, int age, int gender) {
this.personId = id;
this.age = age;
this.gender = gender;
}
public int getPersonId() {
return this.personId;
}
public int getAge() {
return this.age;
}
public int getGender() {
return this.gender;
}
@Override
public String toString() {
return String.format("Person: [%s, %s, %s]", this.personId,this.age,this.gender);
}
}
You can filter your list with this line
persons.stream()
.collect(Collectors.groupingBy(Person::getAge, Collectors.groupingBy(Person::getGender)))