我有两个列表,两个列表具有相同的字段。有些学生在不同的国家有两所房子。我想在合并两个列表时增加studentList2的id字段。我可以使用两个for循环来检查所有列表,但你知道更好的解决方案吗对于这个问题。
List1 是学生列表1
schoolId | id | countryCode | cityCode
5555 1 20 1
5555 1 24 2
5555 2 1 3
5555 3 1 3
5555 4 1 3
List2 是学生列表2
schoolId | id | countryCode | cityCode
6666 1 20 1
6666 1 24 2
6666 2 20 1
6666 2 24 2
6666 3 20 1
6666 3 24 2
6666 4 20 1
6666 4 24 2
6666 5 1 3
6666 6 1 3
我的期望是
schoolId | id | countryCode | cityCode
5555 1 20 1
5555 1 24 2
5555 2 1 3
5555 3 1 3
5555 4 1 3
6666 5 20 1
6666 5 24 2
6666 6 20 1
6666 6 24 2
6666 7 20 1
6666 7 24 2
6666 8 20 1
6666 8 24 2
6666 9 1 3
6666 10 1 3
我可以使用两个 for 循环来比较列表字段,但我想找到更好的解决方案。
这会有帮助吗?您创建一个 Student 类,其中包含国家/地区代码列表和城市列表。您可以使用 Set 来保持其唯一性。
class Scratch {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student(5555, 1, new ArrayList<>(), new ArrayList<>()));
students.get(students.size() - 1).countryCodes.add(20);
students.get(students.size() - 1).countryCodes.add(24);
students.get(students.size() - 1).cityCodes.add(1);
students.get(students.size() - 1).countryCodes.add(2);
students.add(new Student(5555, 2, new ArrayList<>(), new ArrayList<>()));
students.get(students.size() - 1).countryCodes.add(1);
students.get(students.size() - 1).cityCodes.add(3);
int targetStudentId = 5555;
int newCountryCode = 24;
int newCityCode = 2;
for (var student : students) {
if (targetStudentId == student.id) {
student.countryCodes.add(newCountryCode);
student.cityCodes.add(newCityCode);
}
}
}
}
class Student {
Integer schoolId;
Integer id;
List<Integer> countryCodes;
List<Integer> cityCodes;
public Student(Integer schoolId, Integer id, List<Integer> countryCodes, List<Integer> cityCodes) {
this.schoolId = schoolId;
this.id = id;
this.countryCodes = countryCodes;
this.cityCodes = cityCodes;
}
}