In the process of improving the existing legacy code, I tried to reduce the warnings from IntelliJ.
At that time, there was a process of "set the value when the key value is null for Map", but since I learned the point from IntelliJ, I wrote this article.
For example, suppose there is a map with the following prefecture name and prefectural office location.
Map<String, String> prefectures = new HashMap<>();
prefectures.put("Ibaraki Prefecture", "Mito");
prefectures.put("Tochigi Prefecture", "Utsunomiya");
prefectures.put("Gunma Prefecture", null);
Currently, the value of key Gunma prefecture is null, and we want to set the value here. At this time, in the existing implementation, the value was set by the following method.
if (prefectures.get("Gunma Prefecture") == null) {
prefectures.put("Gunma Prefecture", "Maebashi");
}
IntelliJ suggested that you could write it simpler with the putIfAbsent method.
The putIfAbsent method is a method that sets the value when the key is null as above, and if you use this method, the if statement like the previous example disappears and
prefectures.putIfAbsent("Gunma Prefecture", "Maebashi");
You can write clearly in one line.
I didn't know the existence of this method, so it's easy, but I wrote this article this time.
When performing the process of "setting the value when the key value is null for Map", you can write it clearly by using the putIfAbsent method without using the if statement.
I thought again that IntelliJ, which even makes such a proposal, is amazing, but I also wondered how to know such a convenient method.
I would appreciate it if you could tell me if there is a better way than "Look at JavaDoc and take a look" and "Read the JDK release notes".
I hope this article helps someone. Until the end Thank you for reading.
JavaDoc for putIfAbsent method
Recommended Posts