Unwanted code refactoring

As an Engineer, we have our own preferences in writing our code. Our own beliefs in how something should be written and what is the best way to write a piece of logic. When we want to apply our thoughts and ideas on something that is already existing ( which we call it as refactoring ), we should be pretty careful about unexplained internal details of the existing logic or unknowns in our new logic. With refactoring, your goal is not to mess up the existing functionality but to do the same thing in a better or cleaner way ( at least it is a cleaner approach in your own view!!). For example, look at the two pieces of the code below.

List<StudentEntity> allStudents = getMeAllStudents();

final Map<String, StudentEntity> perCityStudents = new HashMap<>(allStudents.size());
allStudents.forEach(unitEntity ->   perCityStudents.put(studentEntity.getCity(), studentEntity));

List<StudentEntity> allStudents = getMeAllStudents();
Map<String, StudentEntity> perCityStudents = allStudents.stream()
.collect(Collectors.toMap(StudentEntity::getCity, studentEntity -> studentEntity));

At the first glance, they both looks like doing the same thing with one using the streams and other is not.

Everything works fine with both of these approaches until there is a key collision. The unexplained (may be self explained as it is a map data structure) detail of the first block of code is, if more than one student belongs to the same city, then we are simply overriding it. At the end, we will get only one student per city. Whereas the Collector in the second piece of the code don’t know what to do with the duplicate keys. You need to explain it to the collector on how to resolve the key conflicts, otherwise it will throw an exception, which I think is a good thing instead of overriding by default. Checkout how to resolve the conflict here.

Just be careful about unexplained things if you are taking up any code refactoring tasks. You don’t want to introduce bugs with unwanted code refactoring.