实现如下所示:
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author 王立朝 * @date 2023/7/19 * @description: */ public class Test2 { public static void main(String[] args) { // 创建用户列表和部门列表 List<User> userList = createUserList(); List<Department> departmentList = createDepartmentList(); // 创建一个映射,将部门ID和部门对象关联起来 Map<Integer, Department> departmentMap = createDepartmentMap(departmentList); // 将用户放到对应部门下 for (User user : userList) { int departmentId = user.getDepartmentId(); if (departmentMap.containsKey(departmentId)) { Department department = departmentMap.get(departmentId); department.addUser(user); } } // 打印部门及其所属用户 for (Department department : departmentList) { System.out.println("部门名称:" + department.getName()); System.out.println("所属用户:"); for (User user : department.getUsers()) { System.out.println(user.getName()); } System.out.println("-------------------"); } } // 创建用户列表 private static List<User> createUserList() { List<User> userList = new ArrayList<>(); userList.add(new User("User1", 1)); userList.add(new User("User2", 2)); userList.add(new User("User3", 1)); userList.add(new User("User4", 3)); userList.add(new User("User5", 2)); return userList; } // 创建部门列表 private static List<Department> createDepartmentList() { List<Department> departmentList = new ArrayList<>(); departmentList.add(new Department(1, "部门A")); departmentList.add(new Department(2, "部门B")); departmentList.add(new Department(3, "部门C")); return departmentList; } // 创建部门ID与部门对象的映射 private static Map<Integer, Department> createDepartmentMap(List<Department> departmentList) { Map<Integer, Department> departmentMap = new HashMap<>(); for (Department department : departmentList) { departmentMap.put(department.getId(), department); } return departmentMap; } } // 用户类 class User { private String name; private int departmentId; public User(String name, int departmentId) { this.name = name; this.departmentId = departmentId; } public String getName() { return name; } public int getDepartmentId() { return departmentId; } } // 部门类 class Department { private int id; private String name; private List<User> users; public Department(int id, String name) { this.id = id; this.name = name; this.users = new ArrayList<>(); } public int getId() { return id; } public String getName() { return name; } public List<User> getUsers() { return users; } public void addUser(User user) { users.add(user); } }
效果如下:
部门名称:部门A 所属用户: User1 User3 ------------------- 部门名称:部门B 所属用户: User2 User5 ------------------- 部门名称:部门C 所属用户: User4 -------------------
标签:java,name,departmentList,List,用户,public,User,new,对应 From: https://www.cnblogs.com/wanglichaoya/p/17566955.html