forked from Java-Techie-jt/java8
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOptionalDemo.java
More file actions
46 lines (30 loc) · 1.48 KB
/
OptionalDemo.java
File metadata and controls
46 lines (30 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.javatechie;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class OptionalDemo {
public static Customer getCustomerByEmailId(String email) throws Exception {
List<Customer> customers = EkartDataBase.getAll();
return customers.stream()
.filter(customer -> customer.getEmail().equals(email))
.findAny().orElseThrow(()->new Exception("no customer present with this email id"));
}
public static void main(String[] args) throws Exception {
Customer customer=new Customer(101, "john", "test@gmail.com", Arrays.asList("397937955", "21654725"));
//empty
//of
//ofNullable
Optional<Object> emptyOptional = Optional.empty();
System.out.println(emptyOptional);
//Optional<String> emailOptional = Optional.of(customer.getEmail());
//System.out.println(emailOptional);
Optional<String> emailOptional2 = Optional.ofNullable(customer.getEmail());
/* if(emailOptional2.isPresent()){
System.out.println(emailOptional2.get());
}*/
// System.out.println(emailOptional2.orElse("default@email.com"));
// System.out.println(emailOptional2.orElseThrow(()->new IllegalArgumentException("email not present")));
System.out.println(emailOptional2.map(String::toUpperCase).orElseGet(()->"default email..."));
getCustomerByEmailId("pqr");
}
}