Yeongjun's Wicksome documents ๐ŸŒฑ

Difference between Optional.orElse() and Optional.orElseGet()

Topics: java, java8

fb-contrib:OI_OPTIONAL_ISSUES_USES_IMMEDIATE_EXECUTION

orElseGet()๋Š” null์ผ ๊ฒฝ์šฐ์—๋งŒ ํ˜ธ์ถœ๋˜๊ณ , orElse()๋Š” ๋ฌด์กฐ๊ฑด ํ˜ธ์ถœ๋œ๋‹ค.

class LocalTest {
	@Test
	void test() {
		System.out.println("1.");
		Optional.ofNullable(null).orElse(new TestObject());		System.out.println("2.");		Optional.ofNullable(new TestObject()).orElse(new TestObject());
		System.out.println("3.");
		Optional.ofNullable(null).orElseGet(TestObject::new);
		System.out.println("4.");
		Optional.ofNullable(new TestObject()).orElseGet(TestObject::new);
	}

	class TestObject {
		private String str;
        
		TestObject() {
			System.out.println("new");
		}
	}
}
1.
new
2.
new
new
3.
new
4.
new

Conclusion

๋ถˆํ•„์š”ํ•œ ํ˜ธ์ถœ์„ ์ค„์ด๊ธฐ ์œ„ํ•ด null์ผ ๊ฒฝ์šฐ ๋ฐ˜ํ™˜ํ•  ๊ฐ’์ด primitive type์ด๋ฉด orElse(), ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•ด์•ผํ•œ๋‹ค๋ฉด orElseGet()๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋  ๊ฒƒ ๊ฐ™๋‹ค.

int value = Optional.ofNullable(obj1).orElse(123);
TestObject object = Optional.ofNullable(obj2).orElseGet(() -> new TestObject());
TestObject object = Optional.ofNullable(obj2).orElseGet(TestObject::new);

References

Comments

Previous Post์ดํŽ™ํ‹ฐ๋ธŒ์ž๋ฐ” 9์žฅ. ์˜ˆ์™ธ (3)
Next PostJava8์—์„œ TimeZone ๋‹ค๋ฃจ๊ธฐ