When I encounter Java 8 on the Internet, objects are manipulated from collections throughout. But there is no use of java8 to operate the contents of the collection in the collection. Now share one myself. From a List<List<User>> collection, take out a certain value of the List collection object inside for your reference. If you have a better way, you are welcome to suggest it.
Example: Find the class of primary school student 1 from a nested set. The following example is the correct answer
public static void main(String[] args) {
// 学生列表
List<User> studentList = Arrays.asList(
new User("小学生1","20","一班",new ArrayList<>()),
new User("小学生2","30","二班",new ArrayList<>()),
new User("小学生3","40","三班",new ArrayList<>())
);
// 员工列表
List<User> employeeList = Arrays.asList(
new User("员工1","20","信息中心",new ArrayList<>()),
new User("员工2","30","科技中心",new ArrayList<>()),
new User("员工3","40","运营中心",new ArrayList<>())
);
// 仆人列表
List<User> servantList = Arrays.asList(
new User("仆人1","20","西房",new ArrayList<>()),
new User("仆人2","30","南房",new ArrayList<>()),
new User("仆人3","40","北房",new ArrayList<>())
);
// 总的集合
List<User> bigList = Arrays.asList(
// 老师下面是学生
new User("老师","20","三年级",studentList),
// 老板下面是工人
new User("老板","30","广发银行",employeeList),
// 主人下面是仆人
new User("主人","40","东房",servantList)
);
// 从bigList 集合中求出小学生1所在班级
String className = bigList.stream()
.filter(user -> "老师".equals(user.getName()))
.map(User::getUserList)
.filter(list -> list != null && list.size()>0)
.flatMap(list -> list.stream()
.filter(user -> "小学生1".equals(user.getName()))
.map(User::getAddress))
.collect(Collectors.joining());
System.out.println("小学生1所在班级:"+className);
}
Improve methods to increase robustness
User entity
package com.test;
import java.util.ArrayList;
import java.util.List;
public class User {
private String name;
private String age;
private String address;
private List<User> userList = new ArrayList<>();
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public User(String name, String age, String address, List<User> userList) {
this.name = name;
this.age = age;
this.address = address;
this.userList = userList;
}
}