Java 9 - Optionele klasseverbeteringen
Optionele klasse is geïntroduceerd in Java 8 om null-controles en NullPointerException-problemen te voorkomen. In Java 9 zijn drie nieuwe methoden toegevoegd om de functionaliteit te verbeteren.
- stream()
- ifPresentOrElse()
- of()
stream()-methode
Syntaxis
public Stream<T> stream()
Als er een waarde aanwezig is, retourneert deze een sequentiële Stream die alleen die waarde bevat, anders wordt een lege Stream geretourneerd.
Voorbeeld
import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; public class Tester { public static void main(String[] args) { List<Optional<String>> list = Arrays.asList ( Optional.empty(), Optional.of("A"), Optional.empty(), Optional.of("B")); //filter the list based to print non-empty values //if optional is non-empty, get the value in stream, otherwise return empty List<String> filteredList = list.stream() .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()) .collect(Collectors.toList()); //Optional::stream method will return a stream of either one //or zero element if data is present or not. List<String> filteredListJava9 = list.stream() .flatMap(Optional::stream) .collect(Collectors.toList()); System.out.println(filteredList); System.out.println(filteredListJava9); } }
Uitvoer
[A, B] [A, B]
ifPresentOrElse() methode
Syntaxis
public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)
Als een waarde aanwezig is, wordt de gegeven actie uitgevoerd met de waarde, anders wordt de gegeven lege actie uitgevoerd.
Voorbeeld
import java.util.Optional; public class Tester { public static void main(String[] args) { Optional<Integer> optional = Optional.of(1); optional.ifPresentOrElse( x -> System.out.println("Value: " + x),() -> System.out.println("Not Present.")); optional = Optional.empty(); optional.ifPresentOrElse( x -> System.out.println("Value: " + x),() -> System.out.println("Not Present.")); } }
Uitvoer
Value: 1 Not Present.
of() methode
Syntaxis
public Optional<T> or(Supplier<? extends Optional<? extends T>> supplier)
Als een waarde aanwezig is, retourneert een Optioneel die de waarde beschrijft, anders retourneert een Optioneel geproduceerd door de leverende functie.
Voorbeeld
import java.util.Optional; import java.util.function.Supplier; public class Tester { public static void main(String[] args) { Optional<String> optional1 = Optional.of("Mahesh"); Supplier<Optional<String>> supplierString = () -> Optional.of("Not Present"); optional1 = optional1.or( supplierString); optional1.ifPresent( x -> System.out.println("Value: " + x)); optional1 = Optional.empty(); optional1 = optional1.or( supplierString); optional1.ifPresent( x -> System.out.println("Value: " + x)); } }
Uitvoer
Value: Mahesh Value: Not Present
Java