Skip to content

Commit

Permalink
OptionalTest
Browse files Browse the repository at this point in the history
  • Loading branch information
javahongxi committed Aug 17, 2019
1 parent 63de768 commit fbf171d
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 0 deletions.
14 changes: 14 additions & 0 deletions whatsmars-common/src/test/java/org/hongxi/java/Address.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package org.hongxi.java;

import lombok.Data;

/**
* Created by shenhongxi on 2019/1/22.
*/
@Data
public class Address {

private String province;

private String city;
}
14 changes: 14 additions & 0 deletions whatsmars-common/src/test/java/org/hongxi/java/User.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package org.hongxi.java;

import lombok.Data;

/**
* Created by shenhongxi on 2019/1/22.
*/
@Data
public class User {

private String name;

private Address address;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package org.hongxi.java.util;

import org.hongxi.java.Address;
import org.hongxi.java.User;

import java.util.Optional;

/**
* Created by shenhongxi on 2019/1/22.
*/
public class OptionalTest {

public static void main(String[] args) {
Optional<String> emptyOpt = Optional.empty();
System.out.println(emptyOpt.isPresent());
System.out.println(emptyOpt.orElse("a"));
System.out.println(emptyOpt.isPresent());
System.out.println(emptyOpt.orElseGet(() -> {
String s1 = "a";
String s2 = "b";
return s1 + s2;
}));

String s = "Hello";
Optional<String> notNullOpt = Optional.of(s);
if (notNullOpt.isPresent()) {
System.out.println(notNullOpt.get());
}
notNullOpt = notNullOpt.filter(s1 -> s1.contains("xyz"));
System.out.println(notNullOpt.isPresent());
}

public static String getName(User user) {
return Optional.ofNullable(user)
.map(User::getName)
.orElse("Unknown");
}

public static String getCity(User user) throws IllegalArgumentException {
return Optional.ofNullable(user)
.map(User::getAddress)
.map(Address::getCity)
.orElseThrow(() -> new IllegalArgumentException("params cant not be null"));
}
}

0 comments on commit fbf171d

Please sign in to comment.