Изменение значения в Map
public static void main(String[] args) {
Student student1 = new Student("Ivan", "Ivanov");
Student student2 = new Student("Nikolay", "Petrov");
Student student3 = new Student("Kirill", "Antipov");
Course matematic = new Course("Matematic");
Course philosophy = new Course("Philosophy");
Course english = new Course("English");
Course physics = new Course("Physics");
Course french = new Course("Franch");
Map<Student, List<Course>> education = new HashMap<Student, List<Course>>();
education.put(student1, Arrays.asList(matematic, english, philosophy));
education.put(student2, Arrays.asList(matematic, english, physics));
education.put(student3, Arrays.asList());
Collection<List<Course>> courses = education.values();
List<Course> updatedCourses = new ArrayList<>();
for (Course course : updatedCourses) {
if (course.equals(education.values())) {
updatedCourses.add(new Course("Franch"));
} else {
updatedCourses.add(new Course("Franch"));
}
for (Entry<Student, List<Course>> entry : education.entrySet()) {
education.put(entry.getKey(),entry.setValue(new ArrayList<Course>()));
}
}
for (Map.Entry entry : education.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
Мне необходимо заменить один объект "курс" на другой. У всех студентов, у которых в значении есть курс english, нужно заменить на frеnch.
Без использования лямбд и стримов. Спасибо за любую помощь.
Ответы (2 шт):
Вовсе не обязательно создавать новый список для каждого ключа (студента). Можно просто проходиться по education.values(), заменяя english на french в случае, если english нашёлся:
for (List<Course> value : education.values()) {
int indexOf = value.indexOf(english);
if (indexOf >= 0) {
value.set(indexOf, french);
}
}
Для замены элементов в списке ещё со времён Java 1.4 существует метод Collections::replaceAll(List<T> list, T oldVal, T newVal).
Соответственно, достаточно проитерироваться по коллекции значений мапы education:
for (List<Course> courses : education.values()) {
Collections.replaceAll(courses, english, french);
}
С использованием Iterable::forEach такая замена превратится в однострочник, правда, при помощи лямбды:
education.values().forEach(courses -> Collections.replaceAll(courses, english, french));