Java 8 Optional
July 13, 2016 Leave a comment
I think there are more elegant ways to check if Optional is empty or not but here I have to collect everything in a ArrayList. So I wasn’t able to include isPresent() in the lambda pipeline.
package com.test; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class OptionalTest { private static List<String> newImports = new ArrayList<>(); public static Optional<List<String>> getOptionalNewImports() { return Optional.ofNullable(newImports); } public static void main( String... argv ){ newImports.add("org.apache.struts"); if( getOptionalNewImports().isPresent() ) { List<String> imports = new ArrayList<>(); getOptionalNewImports().get().stream() .map(p -> "import " + p + ";") .collect(Collectors.toCollection(() -> imports)); imports.forEach( System.out::println); } } }
This is the relevant method.
public Optional<List<String>> getOptionalNewImports() { return Optional.ofNullable(newImports); }
This is a proper usage of ifPresent. I assign a value to a variable if the value is present.
rules.getOptionalClassIdentifier().ifPresent( a -> {this.classIdentifier = a;});