Java代码信息

运行结果
教程手册
代码仓库
极速运行
交互输入
极速运行模式,不支持键盘输入语句但是拥有更高的运行速度,输出简洁明了 。 点击编辑器上方的运行按钮即刻体验吧。
以下是用户最新保存的代码
猜字游戏! 发布于:2021-01-22 10:04 // 保存京东到家sign签名代码 发布于:2021-01-22 15:25 定义 根节点的 深度 是 0,子节点的深度是父节点的 深度 + 1 发布于:2021-01-19 19:40 寻找链表表头 发布于:2021-01-19 19:32 日期时区测试 发布于:2021-01-19 18:45 参考下图,输出 id 和 level 的映射 定义 根节点的 深度 是 0,子节点的深度是父节点的 深度 + 1 发布于:2021-01-19 14:05 寻找链表的头节点,每个节点,有 id 和 nextId 两个属性,nextId 表示指向节点 id。现在请实现一个办法寻找该链表的头节点。 PS. 考虑一下链表环状,以及节点不在链表内等异常情况,出现异常时,打印异常消息即可。 发布于:2021-01-19 13:59 System.in.read()测试 发布于:2021-01-16 23:46 计算100万以内素数 发布于:2021-01-16 21:36 新核云-----题目2 发布于:2021-01-15 00:08 输出 id 和 level 的映射 发布于:2021-01-12 23:55 寻找链表的头节点 发布于:2021-01-12 22:07 新核云后端笔试 - NodeTraverse 发布于:2021-01-12 17:37 新核云后端笔试 - FindFirstNode 发布于:2021-01-12 17:37 九九乘法表 发布于:2021-01-11 16:01 将8进制数转换为十进制数 发布于:2021-01-11 15:56 输入三个数,按从大到小输出 发布于:2021-01-11 15:56 100以内的所有偶数的和 发布于:2021-01-11 15:55 编写一个程序判断字符串“Tom”是否在另一个字符串“I am Tom, I am from China”中出现 发布于:2021-01-11 15:51 编写一个类,类名为Rectangle(矩形),它有两个整型的变量width(宽)和height(高);有一个方法area(),没有参数,返回类型为double,功能是求矩形的面积;还有另一个方法为perimeter()没有参数,返回类型为double,功能是求矩形的周长, 发布于:2021-01-11 15:49 编写这样一个程序找出字符串“My name is Tom, I come from China.”中的大写字母,并打印输出。 发布于:2021-01-11 15:49 任意给出一个十进制整数,将十进制整数转换为二进制数 发布于:2021-01-11 15:48 定义一个一维数组,求出数组的最大值,最小值,平均值。 发布于:2021-01-11 15:47 用mkdir创建目录, 用到File类创建文件对象,list()列函数,isDirectory()判断是否目录函数。 发布于:2021-01-11 15:04 写出N的乘积方法factorial 发布于:2021-01-11 12:37 FileOutputStream与OutputStreamWriter FileInputStream与InputStreamReader append()函数,ready()函数,toString()函数 发布于:2021-01-11 14:05 首先创建文件 test.txt,并把给定的数字以二进制形式写进该文件,同时输出到控制台上。 OutputStream与FileOutputStream创建文件,用write()写入数据,for循环语句组个写入数组数据,但会产生异常。 发布于:2021-01-11 11:34 BufferedReader()总的readLine()函数,注意不需要强制类型转换读取值,用比较字符转函数equals();判断取值是否符合结束条件。 发布于:2021-01-11 09:40 BufferedReader(),用read()函数读取输入内容;一定要抛出异常,否则会出错,强制转化读取的内容为字符类型(char),否则也回归报错。遇到Q退出。 发布于:2021-01-11 09:46 n的阶乘用n!表示 发布于:2021-01-10 20:25 九九乘法表 精简 发布于:2021-01-10 15:31 解密rsa 发布于:2021-01-10 13:56 1-7的阶乘的和方法 发布于:2021-01-09 20:37 程序编写题 发布于:2021-01-09 20:15 大数据一班26杨惠恒 发布于:2021-01-09 18:58 1到7的阶乘的和 02zzg 发布于:2021-01-09 18:29 一百一类的素数精简版 发布于:2021-01-08 20:58 ds03tsh 1到7的阶乘的和 发布于:2021-01-07 22:10 java函数式编程 发布于:2021-01-07 16:21 46 赖赵强 1-100里面的素数 发布于:2021-01-05 21:56 把三个成员变量全部设置为10; 发布于:2021-01-05 21:16 求1到100里面的素数 发布于:2021-01-05 21:14 大数据1班26杨惠恒 发布于:2021-01-05 20:16 初始化时,把三个成员变量全部设置为10 发布于:2021-01-05 20:06 1到100里面的素数 发布于:2021-01-05 20:02 1到100里面的素数 发布于:2021-01-05 19:58 DSH TSH03 一百以内的素数 发布于:2021-01-05 19:36 反写的Hello world! 发布于:2021-01-05 15:29 输出 id 和 level 的映射 发布于:2021-01-04 17:12 测试延时的效果 发布于:2021-01-04 17:01 [更多]
显示目录

Java 8 Optional In Depth

Java 8 has introduced a new class Optional in java.util package. It is used to represent a value is present or absent. The main advantage of this new construct is that No more too many null checks and NullPointerException. It avoids any runtime NullPointerExceptions and supports us in developing clean and neat Java APIs or Applications. Like Collections and arrays, it is also a Container to hold at most one value. Let us explore this new construct with some useful examples.

Advantages of Java 8 Optional:

  1. Null checks are not required.
  2. No more NullPointerException at run-time.
  3. We can develop clean and neat APIs.
  4. No more Boiler plate code

1. Optional Basic example

Optional.ofNullable() method returns a Non-empty Optional if a value present in the given object. Otherwise returns empty Optional.

Optionaal.empty() method is useful to create an empty Optional object.

OptionalBasicExample.java

package com.mkyong;

import java.util.Optional;

public class OptionalBasicExample {

    public static void main(String[] args) {

        Optional<String> gender = Optional.of("MALE");
        String answer1 = "Yes";
        String answer2 = null;

        System.out.println("Non-Empty Optional:" + gender);
        System.out.println("Non-Empty Optional: Gender value : " + gender.get());
        System.out.println("Empty Optional: " + Optional.empty());

        System.out.println("ofNullable on Non-Empty Optional: " + Optional.ofNullable(answer1));
        System.out.println("ofNullable on Empty Optional: " + Optional.ofNullable(answer2));

        // java.lang.NullPointerException
        System.out.println("ofNullable on Non-Empty Optional: " + Optional.of(answer2));

    }

}

Output

Non-Empty Optional:Optional[MALE]
Non-Empty Optional: Gender value : MALE
Empty Optional: Optional.empty

ofNullable on Non-Empty Optional: Optional[Yes]
ofNullable on Empty Optional: Optional.empty

Exception in thread "main" java.lang.NullPointerException
    at java.util.Objects.requireNonNull(Objects.java:203)
    at java.util.Optional.<init>(Optional.java:96)
    at java.util.Optional.of(Optional.java:108)
    //...

2. Optional.map and flatMap

OptionalMapFlapMapExample.java

package com.mkyong;

import java.util.Optional;

public class OptionalMapFlapMapExample {

    public static void main(String[] args) {

        Optional<String> nonEmptyGender = Optional.of("male");
        Optional<String> emptyGender = Optional.empty();

        System.out.println("Non-Empty Optional:: " + nonEmptyGender.map(String::toUpperCase));
        System.out.println("Empty Optional    :: " + emptyGender.map(String::toUpperCase));

        Optional<Optional<String>> nonEmptyOtionalGender = Optional.of(Optional.of("male"));
        System.out.println("Optional value   :: " + nonEmptyOtionalGender);
        System.out.println("Optional.map     :: " + nonEmptyOtionalGender.map(gender -> gender.map(String::toUpperCase)));
        System.out.println("Optional.flatMap :: " + nonEmptyOtionalGender.flatMap(gender -> gender.map(String::toUpperCase)));

    }

}

Output

Non-Empty Optional:: Optional[MALE]
Empty Optional    :: Optional.empty
Optional value   :: Optional[Optional[male]]
Optional.map     :: Optional[Optional[MALE]]
Optional.flatMap :: Optional[MALE]

3. Optional.filter

OptionalFilterExample.java

package com.mkyong;

import java.util.Optional;

public class OptionalFilterExample {

    public static void main(String[] args) {

        Optional<String> gender = Optional.of("MALE");
        Optional<String> emptyGender = Optional.empty();

        //Filter on Optional
        System.out.println(gender.filter(g -> g.equals("male"))); //Optional.empty
        System.out.println(gender.filter(g -> g.equalsIgnoreCase("MALE"))); //Optional[MALE]
        System.out.println(emptyGender.filter(g -> g.equalsIgnoreCase("MALE"))); //Optional.empty

    }

}

Output

Optional.empty
Optional[MALE]
Optional.empty

4. Optional isPresent and ifPresent

Optional.isPresent() returns true if the given Optional object is non-empty. Otherwise it returns false.

Optional.ifPresent() performs given action if the given Optional object is non-empty. Otherwise it returns false.

OptionalIfPresentExample.java

package com.mkyong;

import java.util.Optional;

public class OptionalIfPresentExample {

    public static void main(String[] args) {

        Optional<String> gender = Optional.of("MALE");
        Optional<String> emptyGender = Optional.empty();

        if (gender.isPresent()) {
            System.out.println("Value available.");
        } else {
            System.out.println("Value not available.");
        }

        gender.ifPresent(g -> System.out.println("In gender Option, value available."));

        //condition failed, no output print
        emptyGender.ifPresent(g -> System.out.println("In emptyGender Option, value available."));

    }

}

Output

Value available.
In gender Option, value available.

5. Optional orElse methods

It returns the value if present in Optional Container. Otherwise returns given default value.

OptionalOrElseExample.java

package com.mkyong;

import java.util.Optional;

public class OptionalOrElseExample {

    public static void main(String[] args) {

        Optional<String> gender = Optional.of("MALE");
        Optional<String> emptyGender = Optional.empty();

        System.out.println(gender.orElse("<N/A>")); //MALE
        System.out.println(emptyGender.orElse("<N/A>")); //<N/A>

        System.out.println(gender.orElseGet(() -> "<N/A>")); //MALE
        System.out.println(emptyGender.orElseGet(() -> "<N/A>")); //<N/A>

    }

}

Output

MALE
<N/A>
MALE
<N/A>

6. Without Java 8 Optional

As everyone is familiar with Online Shopping. Let us assume that we want to implement a Mobile Product Module for a famous e-Commerce website.

Let us implement Mobile Domain module Without Java 8 Optional.

ScreenResolution.java

package com.mkyong.without.optional;

public class ScreenResolution {

    private int width;
    private int height;

    public ScreenResolution(int width, int height){
        this.width = width;
        this.height = height;
    }

    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }

}

DisplayFeatures.java

package com.mkyong.without.optional;

public class DisplayFeatures {

    private String size; // In inches
    private ScreenResolution resolution;

    public DisplayFeatures(String size, ScreenResolution resolution){
        this.size = size;
        this.resolution = resolution;
    }

    public String getSize() {
        return size;
    }
    public ScreenResolution getResolution() {
        return resolution;
    }

}

Mobile.java

package com.mkyong.without.optional;

public class Mobile {

    private long id;
    private String brand;
    private String name;
    private DisplayFeatures displayFeatures;
    // Likewise we can see Memory Features, Camera Features etc.

    public Mobile(long id, String brand, String name, 
                            DisplayFeatures displayFeatures){
        this.id = id;
        this.brand = brand;
        this.name = name;
        this.displayFeatures = displayFeatures;
    }

    public long getId() {
        return id;
    }

    public String getBrand() {
        return brand;
    }

    public String getName() {
        return name;
    }

    public DisplayFeatures getDisplayFeatures() {
        return displayFeatures;
    }

}

Here if we observe getMobileScreenWidth() method, it has lot of boiler plate code with lots null checks. Before Java 8, we should do all these non-sense stuff to avoid Runtime NullPointerExceptions.

MobileService.java

package com.mkyong.without.optional;

public class MobileService {

    public int getMobileScreenWidth(Mobile mobile){

        if(mobile != null){
            DisplayFeatures dfeatures = mobile.getDisplayFeatures();
            if(dfeatures != null){
                ScreenResolution resolution = dfeatures.getResolution();
                if(resolution != null){
                    return resolution.getWidth();
                }
            }
        }
        return 0;

    }

}

Develop one test application to test these Domain objects.

MobileTesterWithoutOptional.java

package com.mkyong.without.optional;

public class MobileTesterWithoutOptional {

    public static void main(String[] args) {

        ScreenResolution resolution = new ScreenResolution(750,1334);
        DisplayFeatures dfeatures = new DisplayFeatures("4.7", resolution);
        Mobile mobile = new Mobile(2015001, "Apple", "iPhone 6s", dfeatures);

        MobileService mService = new MobileService();

        int mobileWidth = mService.getMobileScreenWidth(mobile);
        System.out.println("Apple iPhone 6s Screen Width = " + mobileWidth);

        ScreenResolution resolution2 = new ScreenResolution(0,0);
        DisplayFeatures dfeatures2 = new DisplayFeatures("0", resolution2);
        Mobile mobile2 = new Mobile(2015001, "Apple", "iPhone 6s", dfeatures2);        
        int mobileWidth2 = mService.getMobileScreenWidth(mobile2);
        System.out.println("Apple iPhone 16s Screen Width = " + mobileWidth2);

    }

}

Output

Apple iPhone 6s Screen Width = 750
Apple iPhone 16s Screen Width = 0

7. With Java 8 Optional

Now develop same domain models using Java 8 Optional construct with clean and neat way.

P.S ScreenResolution.java no change. Please refer above section.

DisplayFeatures.java

package com.mkyong.with.optional;

import java.util.Optional;

public class DisplayFeatures {

    private String size; // In inches
    private Optional<ScreenResolution> resolution;

    public DisplayFeatures(String size, Optional<ScreenResolution> resolution){
        this.size = size;
        this.resolution = resolution;
    }

    public String getSize() {
        return size;
    }
    public Optional<ScreenResolution> getResolution() {
        return resolution;
    }

}

Mobile.java

package com.mkyong.with.optional;

import java.util.Optional;

public class Mobile {

    private long id;
    private String brand;
    private String name;
    private Optional<DisplayFeatures> displayFeatures;
    // Like wise we can see MemoryFeatures, CameraFeatures etc.
    // For simplicity, using only one Features

    public Mobile(long id, String brand, String name, Optional<DisplayFeatures> displayFeatures){
        this.id = id;
        this.brand = brand;
        this.name = name;
        this.displayFeatures = displayFeatures;
    }

    public long getId() {
        return id;
    }

    public String getBrand() {
        return brand;
    }

    public String getName() {
        return name;
    }

    public Optional<DisplayFeatures> getDisplayFeatures() {
        return displayFeatures;
    }

}

Here we can observe that how clean our getMobileScreenWidth() API without null checks and boiler plate code. We don not worry about NullPointerExceptions at run-time.

MobileService.java

package com.mkyong.with.optional;

import java.util.Optional;

public class MobileService {

  public Integer getMobileScreenWidth(Optional<Mobile> mobile){
    return mobile.flatMap(Mobile::getDisplayFeatures)
         .flatMap(DisplayFeatures::getResolution)
         .map(ScreenResolution::getWidth)
         .orElse(0);

  }

}

Now develop one test component

MobileTesterWithOptional.java

package com.mkyong.with.optional;

import java.util.Optional;

public class MobileTesterWithOptional {

  public static void main(String[] args) {
    ScreenResolution resolution = new ScreenResolution(750,1334);
    DisplayFeatures dfeatures = new DisplayFeatures("4.7", Optional.of(resolution));
    Mobile mobile = new Mobile(2015001, "Apple", "iPhone 6s", Optional.of(dfeatures));

    MobileService mService = new MobileService();

    int width = mService.getMobileScreenWidth(Optional.of(mobile));
    System.out.println("Apple iPhone 6s Screen Width = " + width);

    Mobile mobile2 = new Mobile(2015001, "Apple", "iPhone 6s", Optional.empty());        
    int width2 = mService.getMobileScreenWidth(Optional.of(mobile2));
    System.out.println("Apple iPhone 16s Screen Width = " + width2);
  }
}

Output

Apple iPhone 6s Screen Width = 750
Apple iPhone 16s Screen Width = 0

8. Where does Java Optional fits?

If we observe above real-time Retail Domain use-case, we should know that Java Optional construct is useful at the following places.

8.1 Method Parameter

public void setResolution(Optional<ScreenResolution> resolution) {
    this.resolution = resolution;
}

8.2 Method Return Type

public Optional<ScreenResolution> getResolution() {
    return resolution;
}

8.3 Constructor Parameter

public DisplayFeatures(String size, Optional<ScreenResolution> resolution){
    this.size = size;
    this.resolution = resolution;
}

8.4 Variable Declaration

private Optional<ScreenResolution> resolution;

8.5 Class Level

public class B

public class A<T extends Optional<B>> { }

Download Source Code

Download – Java8Optional-example.zip (4 KB)

References

  1. OptionalJavaDoc
由JSRUN为你提供的Java在线工具
        JSRUN提供的Java在线运行,Java 在线编译工具,基于linux操作系统环境提供线上编译和线上运行,具有运行快速,运行结果与常用开发、生产环境保持一致的特点。

title

使用此草稿 删除草稿

皮肤:

运行模式:

嵌入代码 iframe嵌入: