Java 9 Series Part 7: Java util. Optional optimization and enhancement

I plan to write a series of articles about Java 9 in the following period of time. Although Java 9 is not the core Java version like Java 8 or Java 11, there are still many features worthy of attention. I hope you can pay attention to me. I will write java 9 into a series of articles, about ten, and this article is the seventh.

java.util.Optional is a new class in the Java 8 version, which can improve the problem of NullPointException in the programming process to a certain extent. Some methods have been added to this class in Java 9 for enhancement. Let's take a look at it together and review its usage in Java 8.

1, Ifpresentoelse (consumer, Runnable) in Java 9

1.1. Enhancements in Java 9

If a value exists, the new method will execute the given Consumer operation, otherwise it will run the given Runnable operation. The following code first uses the Stream stream Stream of Java 8 to filter the multiples of 3, and then finds the multiples of the first 3 through findFirst. If such a value is found, it will be printed out on the print console; If no such value is found, output "multiple of 3 not found"

The semantics of ifPresent or else (Consumer, Runnable) can be interpreted as: ifPresent is Consumer, or else is Runnable. This is an enhancement method only available in Java 9.

 IntStream.of(1, 2, 4)
          .filter(i -> i % 3 == 0)
          .findFirst()
          .ifPresentOrElse(System.out::println, () -> {  
              System.out.println("Multiple of 3 not found");
          });

There is no multiple of 3 in 1, 2 and 4, so the output results are as follows

Multiple of 3 not found

If the following 2, 6 and 8 arrays are filtered, the final console output result is: 6

 IntStream.of(2, 6, 8)
          .filter(i -> i % 3 == 0)
          .findFirst()
          .ifPresentOrElse(System.out::println, () -> {
              System.out.println("Multiple of 3 not found");
          });   // 6

1.2. Review the writing in Java 8

Java 8 Optional.isPresent():

If you use Java 8 and there is no ifpresentoelse (consumer, Runnable) method, you should write the same code as above: write if and else yourself to judge. Same output: multiple of 3 not found

 OptionalInt opt = IntStream.of(1, 2, 4)
                            .filter(i -> i % 3 == 0)
                            .findFirst();
 if (opt.isPresent()) {
     System.out.println(opt.getAsInt());
 } else {
     System.out.println("Multiple of 3 not found");
 }

Java 8 Optional.ifPresent():

ifPresent() method does not provide an optional operation when the value does not exist. So after the following code is executed, there is no orElse action and no output, which is not very friendly.

 IntStream.of(1, 2, 4)
          .filter(i -> i % 3 == 0)
          .findFirst()
          .ifPresent(System.out::println);

Java 8 Optional.orElse():

The orElse() method gives a default value after the return value of value is null. A default value of - 1 is given in the following code.

 int result = IntStream.of(1, 2, 4)
                       .filter(i -> i % 3 == 0)
                       .findFirst()
                       .orElse(-1);
 System.out.println(result);   //-1

2, Java 9's optional or(Supplier)

This method generates a new option when the value cannot be found. The following code filters the array ['a ',' B ',' C ']. IsDigit determines whether there are numeric characters in the array. Obviously, there is no such value, so findFirst cannot find such a value. So a default value is generated: Optional of('0')

 char digit = Stream.of('a', 'b', 'c')
                    .filter(e -> Character.isDigit(e))
                    .findFirst()
                    .or(() -> Optional.of('0')).get();
 System.out.println(digit);   //0

orElseGet() in Java 8

Optional. In Java 8 The orElseGet() method has the same function. The following code filters the array ['a ',' B ',' C ']. IsDigit determines whether there are numeric characters in the array. Obviously, there is no such value, so findFirst cannot find such a value. So get a default value through orElseGet: '0'

 char result = Stream.of('a', 'b', 'c')
                    .filter(c -> Character.isDigit(c))
                    .findFirst()
                    .orElseGet(()->'0');
 System.out.println(result);   //0

3, Java 9's optional stream()

In this case, optional The Stream () method returns a Stream stream that contains only one maximum element. If the value does not exist, an empty Stream is returned:

 OptionalInt opt1 = IntStream.of(2, 5, 6).max();  //Find the maximum value
 OptionalInt opt2 = IntStream.of(1, 3, 7).max();  //Find the maximum value
 IntStream.concat(opt1.stream(), opt2.stream())  //Merge 2 streams
          .forEach(System.out::println);   //Print the merged stream data

The console outputs the following results:

 6
 7

Welcome to my blog. There are many collections of boutiques in it

Reprint of this article shall indicate the source (it must be connected, not just text): Letter brother blog - zimug.com

If you think it's helpful to you, please give me some praise and share! Your support is my inexhaustible creative power. In addition, the author recently output the following high-quality content, looking forward to your attention.

Tags: Spring

Posted by Takuma on Wed, 11 May 2022 08:12:30 +0300