考虑学生班:
public Student(String name, Address add) {
super();
this.name = name;
this.add = add;
}
private String name;
private Address add;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAdd() {
return add;
}
public void setAdd(Address add) {
this.add = add;
}
}
和地址类:
class Address{
public Address(String city, String state) {
super();
this.city = city;
State = state;
}
private String city;
private String State;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return State;
}
public void setState(String state) {
State = state;
}
}
现在,如果我想根据属于 Address 类的 City & State 对 Student 进行分组:
Student s1 = new Student("Rohit", new Address("Mumbai", "MH"));
Student s2 = new Student("Sudeep", new Address("Mumbai", "MH"));
Student s3 = new Student("Amit", new Address("Pune", "MH"));
Student s4 = new Student("Rahul", new Address("Blore", "KR"));
Student s5 = new Student("Vishal", new Address("Blore", "KR"));
List<Student> st = Arrays.asList(s1,s2,s3,s4,s5);
Function<Student, String> compositeKey = studRecord -> studRecord.getAdd().getCity()+":"+ studRecord.getAdd().getState();
Map<String, List<Student>> groupedStudent = st.stream()
.collect(Collectors.groupingBy(compositeKey));