消费Optional值
可选值存在的情况下消费该值
ifPresent,接受一个函数,存在则传递,否则不发生事情
optionalValue.ifPresent(v -> Process v);
值存在,添加到集合中:
optionalValue.ifPresent(v->results.add(v));
或者直接调用:optionalValue.ifPresent(result::add);
ifPresentOrElse,存在与否执行两套动作
optionalValue.ifPresentOrElse(v->System.out.println("发现"+v),()->logger.warning("不匹配"));
综合案例ifPresent
package streams.optional;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.logging.Logger;
public class OptionalIfPresent {
public static void main(String[] args) throws IOException {
// Path相对路径是指JavaCore2
var contents = Files.readString(Path.of("./resources/alice.txt"));
List<String> words = List.of(contents.split("\\PL+"));
List results = new ArrayList<String>();
// ifPresent
Optional<String> startsWithQ = words.stream().filter(s -> s.startsWith("Q")).findFirst();
startsWithQ.ifPresent(s -> System.out.println(s));
// ifPresent(lambda)
startsWithQ.ifPresent(s -> results.add(s));
System.out.println(results);
// ifPresentOrElse
startsWithQ.ifPresentOrElse(s -> System.out.println("找到: " + s),
() -> Logger.getAnonymousLogger().warning("不匹配"));
}
}
标签:util,ifPresent,Java,results,II,import,java,Optional
From: https://blog.csdn.net/qq_36324341/article/details/144886089