失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > java可选参数_Java可选

java可选参数_Java可选

时间:2018-11-24 01:24:47

相关推荐

java可选参数_Java可选

java可选参数

In this article, we’ll explore Java Optional class which was introduced in Java 8.

在本文中,我们将探讨Java 8中引入的Java Optional类。

Java可选 (Java Optional)

One of the most frequently exception in java programming is NullPointerException. A Null value often represents an absence of value which has to be handled before proceeding with the usual business logic, which leads to unnecessary null checks.NullPointerException是Java编程中最常见的异常之一。 Null值通常表示缺少值,必须在继续进行常规业务逻辑之前先进行处理,这会导致不必要的null检查。 To handle such boiler plate code for null check situations, Java 8 introducedOptionalclass. In this article, we’ll look into details how Java 8 Optional class API helps us to deal with null values.为了在空检查情况下处理此类样板代码,Java 8引入了Optional类。 在本文中,我们将详细研究Java 8 Optional类API如何帮助我们处理空值。 Java 8 stream API and collection methods can returnOptionalobjects. It may or may not contain a non-null value. There are various methods available in the API to deal with the Optional value in a convenient and reliable manner.Java 8流 API和收集方法可以返回Optional对象。 它可能包含也可能不包含非null值。 API中提供了多种方法,以方便,可靠的方式处理Optional值。 Java Optional is a final class.Java Optional是最终课程。

Java 8可选示例 (Java 8 Optional Example)

Let’s look at an example to get the clear idea when it would be helpful to use the objects ofOptionalclass.

让我们看一个示例,以便在使用Optional类的对象会有所帮助时获得清晰的想法。

List<String> listOfStrings = Arrays.asList("Mark", "Howard", "Anthony D'Cornian");Optional<String> largeString = listOfStrings.stream().filter(str -> str.length() > 10).findAny();largeString.ifPresent(System.out::println);Optional<String> veryLargeString = listOfStrings.stream().filter(str -> str.length() > 20).findAny();veryLargeString.ifPresent(System.out::println);

Output:

输出:

Anthony D'Cornian

As we can see, we want to filter the list of strings and get a value whose length is greater than a threshold value.

如我们所见,我们要过滤字符串列表 ,并获得一个长度大于阈值的值。

Such values may or may not exist in the list.OptionalAPI would be a perfect choice to use in such situations. As you can see it hasifPresentmethod which lets us define what to do with the value, if we get any.

列表中可能存在也可能不存在这样的值。OptionalAPI是在这种情况下使用的理想选择。 如您所见,它具有ifPresent方法,该方法可以让我们定义如何处理该值(如果有)。

In our case,veryLargeStringwill not contain any value so nothing will get printed.

在我们的例子中,veryLargeString将不包含任何值,因此不会打印任何内容。

Java 8 Optional API provides several such methods. In the next sections, we’ll explore them in detail.

Java 8 Optional API提供了几种这样的方法。 在下一部分中,我们将详细探讨它们。

Java可选方法 (Java Optional Methods)

static Optional empty(): It creates and returns an emptyOptionalinstance.static Optional empty():它创建并返回一个空的Optional实例。boolean isPresent(): It return true if there is a value present, otherwise false.

Optional<String> empty = Optional.empty();System.out.println(empty.isPresent());

boolean isPresent():如果存在值,则返回true,否则返回false。

Optional<String> empty = Optional.empty();System.out.println(empty.isPresent());

void ifPresent(Consumer consumer): If a value is present, this method invokes the specified consumer with the value, otherwise does nothing. As we can see, in our first example:

largeString.ifPresent(System.out::println);

gave output:

void ifPresent(Consumer consumer):如果存在值,则此方法使用该值调用指定的使用者,否则不执行任何操作。 如我们所见,在第一个示例中:

largeString.ifPresent(System.out::println);

给出了输出:

T get(): If a value is present in the Optional, this method returns the value, otherwise throws NoSuchElementException. As you might have gussed

System.out.println(largeString.get());

will also print

T get():如果Optional中存在值,则此方法返回该值,否则抛出NoSuchElementException。 如您所料

System.out.println(largeString.get());

也将打印

T orElse(T otherValue): This method returns the value if present, otherwise returns the otherValue provided in the argument. When we are not sure whetherOptionalwill contain value, it’s always good idea to use this method rather than simpleget().

Optional<String> empty = Optional.empty();System.out.println(empty.orElse("Default Value"));

will print:

There is alsoorElseGet(Supplier other)method available, which calls supplier function or executes lambda to get the value instead of returning hard coded value.

System.out.println(empty.orElseGet(() -> "Default Value"));

will also print the same value.

T orElse(T otherValue):此方法返回值(如果存在),否则返回参数中提供的otherValue。 当我们不确定Optional是否将包含值时,最好使用此方法,而不是简单的get()

将打印:

Default Value

也可以使用orElseGet(Supplier other)方法,该方法调用供应商函数或执行lambda以获取值,而不是返回硬编码值。

也将打印相同的值。

static Optional<T> of(T value): It returns an Optional with the specified present non-null value.

Optional<String> opt = Optional.of("static value");

static Optional<T> of(T value):它返回带有指定的当前非空值的Optional。Optional filter(Predicate predicate): It takes a predicate as an argument and returns an Optional object. If condition of the predicate is met, then the Optional is returned as is, Otherwise it will return an emptyOptional.

Optional<Integer> intOptional = Optional.of(34);Optional<Integer> evenIntOptional = intOptional.filter(i -> i % 2 == 0);System.out.println(evenIntOptional.orElse(0));Optional<Integer> oddIntOptional = intOptional.filter(i -> i % 2 != 0);System.out.println(oddIntOptional.orElse(0));

Output:

Optional filter(Predicate predicate):它将谓词作为参数并返回Optional对象。 如果满足谓词的条件,则按原样返回Optional,否则将返回空的Optional

Optional<Integer> intOptional = Optional.of(34);Optional<Integer> evenIntOptional = intOptional.filter(i -> i % 2 == 0);System.out.println(evenIntOptional.orElse(0));Optional<Integer> oddIntOptional = intOptional.filter(i -> i % 2 != 0);System.out.println(oddIntOptional.orElse(0));

输出:

There are alsoequals(),hashcode()andtoString()methods available in the Optional API.

可选API中还提供equals()hashcode()toString()方法。

Java 9可选类增强 (Java 9 Optional Class enhancements)

Java 9 introduced few extra methods in Optional class:

Java 9在Optional类中引入了一些额外的方法:

public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction): If a value is present, performs the given action with the value, otherwise performs the given empty-based action.public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction):如果存在值,则使用该值执行给定的操作,否则执行给定的基于空的操作。public Optional<T> or(Supplier<? extends Optional<? extends T>> supplier): If a value is present, returns an Optional describing the value, otherwise returns an Optional produced by the supplying function.public Optional<T> or(Supplier<? extends Optional<? extends T>> supplier): If a value is present, returns an Optional describing the value, otherwise returns an Optional produced by the supplying function.public Stream<T> stream(): If a value is present, returns a sequential Stream containing only that value, otherwise returns an empty Stream.public Stream<T> stream():如果存在值,则返回仅包含该值的顺序Stream,否则返回空Stream。

That’s all for the Java Optional class. You should also check out java 8 features.

这就是Java Optional类的全部内容。 您还应该查看Java 8功能 。

Reference: API Doc

参考: API文档

翻译自: /16709/java-optional

java可选参数

如果觉得《java可选参数_Java可选》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。