Keep the value in Map If there is already a value in Map, it is the story when I implemented it to use that.
that time, Map # put () does not return the put value as it is, I couldn't write it as I expected, that is, it's a complaint: cry: (Specifically, refer to the source code: pencil :)
※perhaps, There may be a smart solution and Maybe it's just a misunderstanding: thinking:
Main.java
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
//Ideal (I want to write like this)
String idealKey = "idealKey";
Map<String, String> idealMap = new HashMap<String, String>();
String idealValue = Optional.ofNullable(
idealMap.get(idealKey)
).orElseGet(
//put returns null ...
() -> idealMap.put(idealKey, "idealValue")
);
System.out.println("get:" + idealValue);
//Reality (I ended up writing this)
String realKey = "realKey";
Map<String, String> realMap = new HashMap<String, String>();
String realStr = Optional.ofNullable(
realMap.get(realKey)
).orElseGet(() -> {
String value = "realValue";
realMap.put(realKey, value);
return value;
});
System.out.println("get:" + realStr);
}
}
get:null
get:realValue
Recommended Posts