LoginSignup
0
0

More than 5 years have passed since last update.

Java8のOptionalとstreamメモ

Last updated at Posted at 2018-02-11
  • javadocを見なくても値がnullかもよってこと。

ソースコード

Sample.java
package sample;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class Sample {
    private final static List<Integer> INTEGER_LIST = Arrays.asList(new Integer[] { 1, 2, null });

    public static Optional<Integer> get(int index) {
        Integer val;
        try {
            val = INTEGER_LIST.get(index);
        } catch (Exception e) {
            val = null;
        }
        return Optional.ofNullable(val);
    }
}
Main.java
package sample;

import java.util.Optional;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        IntStream.range(0, 10).mapToObj(Sample::get).filter(Optional::isPresent).map(Optional::get)
                .forEach(System.out::println);
    }
}

実行結果

sh-3.2$ java -jar optional.jar
1
2
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0