Java 8 Streams API [Part 1]| optional Usage and Best Practices

Chiwa Kantawong (Pea)
3 min readAug 2, 2021

--

คลาส Optional อยู่ใน java.util ซึ่งเป็นคลาสที่เอามาเพื่อแก้ปัญหา NullPointerException โดยเฉพาะเลย (เพื่อนแท้ Programmer)

กล้าสาบานไหมว่าไม่เคยเขียนโปรแกรมแล้วเจอ NullPointerExeption ?

package com.zengcode.demo;


public class OptionalDemo {

public static void main(String[] args) {
String name = null;
System.out.println(name.length());
}
}

จาก code ข้างต้นคงพอจะดำอออกนะครับว่า output จะเป็นอะไร

กรณีนี้เราสามารถใช้ Optional มาช่วยได้คือ Optional จะมาทำการ wrapper object ที่เราต้องการ และสามารถดำเนินการต่างๆ กับ object นั้นได้

Ex 1.

package com.zengcode.demo;


import java.util.Optional;

public class OptionalDemo {

public static void main(String[] args) {
Optional<String> name = Optional.empty();
if (name.isPresent())
System.out.println(name.get().length());
}
}

Ex 2.

package com.zengcode.demo;

import java.util.Optional;

public class OptionalDemo {

public static void main(String[] args) {
Customer customer = new Customer(1, null);
System.out.println(Optional.ofNullable(customer.getName()));
}

public static class Customer {
private int id;
private String name;

public Customer(int id, String name) {
this.id = id;
this.name = name;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}
}

บรรทัด System.out.println(Optional.ofNullable(customer.getName()));

จะไม่ให้ NPE ออกมานะครับจะให้ค่า Optional.empty ออกมาแทน

Ex 3.

package com.zengcode.demo;

import java.util.Optional;

public class OptionalDemo {

public static void main(String[] args) {
Customer customer = new Customer(1, null);
Optional<String> customerNameOption = Optional.ofNullable(customer.getName());
System.out.println(customerNameOption.orElse("Chiwa"));
}

public static class Customer {
private int id;
private String name;

public Customer(int id, String name) {
this.id = id;
this.name = name;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}
}

orElse จะเป็นการระบุค่า default ให้ถ้า option ที่เราเรียกไม่มีค่า จากตัวอย่างข้างต้นเราก็จะได้ค่า Chiwa ออกมา

Ex 4.

เราสามารถ Throw Exception ได้ถ้าเกิด option ที่เราเรียกใช้ไม่มีค่าเช่น

ซึ่งเราก็สามารถสร้าง Custom Excption ได้นะครับ

Ex 5.

Filter แบบง่ายๆ จากตัวอย่างจะมี list ของ customer อยู่ เราจะมา filter เอา customer ที่มีชื่อว่า Nabee ออกมา แล้วก็ print id ออกมา ก็คือ 3 นั่นเอง

จากตัวอย่างนี้

เราสามารถ ใช้ orElse() หรือ orElseThrow() ได้เช่นเดียวกับ option นะครับ

อีกสักตัวอย่างนะ

package com.zengcode.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class OptionalDemo {

public static void main(String[] args) {
Customer customer = new Customer(1, "Chiwa");
Customer customer2 = new Customer(2, "Chiwee");
Customer customer3 = new Customer(3, "Nabee");
List<Customer> customerList = new ArrayList<>();
customerList.add(customer);
customerList.add(customer2);
customerList.add(customer3);

List<Customer> customerList2 = customerList.stream().filter(cust -> cust.getName().startsWith("Chi"))
.collect(Collectors.toList());

System.out.println(customerList2.toString());


}

public static class Customer {
private int id;
private String name;

public Customer(int id, String name) {
this.id = id;
this.name = name;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "Customer{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
}

เราจะ filter customer ที่มีชื่อขึ้นต้นด้วย Chiwa มาใส่ อีก list นึง

มันต้องมีโอกาสได้ใช้ครับแล้วเราก็จะใช้มันได้คล่อง ลองศึกษาดูนะครับ จริงๆ มันทำอะไรได้เยอะแยะมากกว่านี้ บทความนี้เอาแค่หอมปากหอมคอกันนะครับ

--

--

Chiwa Kantawong (Pea)
Chiwa Kantawong (Pea)

Written by Chiwa Kantawong (Pea)

Software Development Expert at Central Tech

No responses yet