我想在系统中做一个深层数据。我有这样的课程:
Class User{
User mother;
User father;
User spouse;
}
创建单个记录后,我想重建它们的引用:
Map<User, User> motherMap = new HashMap<User, User>();
Map<User, User> fatherMap = ...;
Map<User, User> spouseMap = ...;
//Now I want to populate User reference like this:
for(User user : motherMap.keySet) {
//some other similar code;
user.setMother(motherMap.get(user));
}
for(User user : fatherMap.keySet) {
//some other similar code;
user.setFather(fatherMap.get(user));
}
for(User user : motherMap.keySet) {
//some other similar code;
user.setSpouse(spouseMap.get(user));
}
知道如何清理这种类似的代码吗?我想让我的代码更好,因为在实际代码中,用户之间有超过10个引用。 Intellij警告说这个方法太复杂了,无法分析,我觉得我只做复制粘贴...
答案 0 :(得分:1)
您可以这样做,从所有地图创建一组所有键:
Set<User> allUsers = new HashSet<User>();
allUsers.addAll(motherMap.keySet());
allUsers.addAll(fatherMap.keySet());
allUsers.addAll(spouseMap.keySet());
for (User u : allUsers) {
u.setMother(motherMap.get(u));
u.setFather(fatherMap.get(u));
u.setSpouse(spouseMap.get(u));
}
答案 1 :(得分:-2)
您是否尝试过使用
过滤课程instance of