lang/java

Java Optional

C/H 2023. 6. 7. 13:35
package org.example;

import java.util.Optional;

public class OptionalTest {

    public static void main(String[] args) {
        System.out.println("Hello world!");

        for (int i : new int[]{0, 1}) {
            System.out.println(i);
        }

        Object val;
        boolean is;

        val = Optional.of("ABCD").filter(v -> v.startsWith("AB")).orElse("Not AB");
        System.out.println(val);

        val = Optional.of("XYZ").filter(v -> v.startsWith("AB")).orElse("Not AB");
        System.out.println(val);

        val = Optional.of("XYZ").map(String::toLowerCase).orElse("Not AB");
        System.out.println(val);

        val = Optional.of("XYZ").map(String::toUpperCase).orElse("Not AB");
        System.out.println(val);

        is = Optional.of("XYZ").isPresent();
        System.out.println(is);

        is = Optional.of("XYZ").filter(v -> "Not Equals".equals(v)).isPresent();
        System.out.println(is);

        Optional.of("TEST").ifPresent(System.out::println);
        Optional.ofNullable(null).ifPresent(System.out::println);
        Optional.ofNullable("ofNullable").ifPresent(System.out::println);

        val = Optional.of("TEST").get();
        System.out.println(val);

        try {
            val = Optional.ofNullable(null).get();
        }catch (Exception e){
//            e.printStackTrace();
        }

        val = Optional.of("ZEN").filter(v -> v.startsWith("AB")).orElse("Not AB");
        System.out.println(val);

        val = Optional.ofNullable("ZEN").filter(v -> v.startsWith("AB")).orElseGet(() -> "Not AB");
        System.out.println(val);

        /*
        try {
            Optional.ofNullable("XYZ").filter(v -> v.startsWith("AB")).orElseThrow(NoSuchFieldException::new);
        } catch (Exception e) {
            e.printStackTrace();
        }/**/

        System.out.println("#################");
        System.out.println("ITP07".matches("^ITP05|ITP06|ITP07$"));
    }
}
> Task :OptionalTest.main()
Hello world!
0
1
ABCD
Not AB
xyz
XYZ
true
false
TEST
ofNullable
TEST
Not AB
Not AB
#################
true
반응형

'lang > java' 카테고리의 다른 글

Java isInstance  (0) 2023.06.08
Java System.getenv  (0) 2023.06.08
Java Date Offset  (0) 2023.06.07
Java - 2 ArrayList join LinkedHapMap Filter to CSV String  (0) 2022.02.23
java filter speed Test  (0) 2021.12.31