0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Optionalを初めて使ってみて感じた、理想と現実 ~Mapを使ったキャッシュの実装編 ~

Last updated at Posted at 2020-07-19

概要

Mapに値を保持しておいて、
既にMapに値があれば、そちらを使うように実装した時の話です。

その際、
Map#put()がputした値をそのまま返却してくれず、
理想通りに書けなかったという、つまり愚痴です :cry:
(具体的にはソースコード参照 :pencil:

※もしかすると、
 スマートな解決方法はあるかもしれませんし、
 ただの勘違いかもしれません :thinking:

ソースコード

Main.java
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        // 理想(こう書きたい)
        String idealKey = "idealKey";
        Map<String, String> idealMap = new HashMap<String, String>();
        String idealValue = Optional.ofNullable(
	        idealMap.get(idealKey)
        ).orElseGet(
            // putはnullを返す…
            () -> idealMap.put(idealKey, "idealValue")
        );
        System.out.println("get:" + idealValue);

        // 現実(こう書くことになった)
        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
0
0
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?