Java 8--optional

Source: Internet
Author: User

This article mainly introduces the Java 8 Optional simple use of

Address
1234567 @Data @AllArgsConstructor @NoArgsConstructor public class Address {private String province; private String city;}
of + ofnullable

Related code hosted in Java8_demo

123456789101112131415161718 @Test (expected = nosuchelementexception.class)public void emptytest() { //Declare an empty optional objectoptional<address> nameoptional = Optional.empty ();//Java.util.NoSuchElementException:No value presentNameoptional.get ();}@Test (expected = nullpointerexception.class)public void ofnulltest() { //Create a optional object from an instanceOptional.of (New Address ("Guangdong", "Zhongshan")); //optional.ofnullable (NULL) returns Optional.empty ()Assertequals (Optional.empty (), Optional.ofnullable (null));//Java.lang.NullPointerExceptionOptional.of (null);}

Map
    1. Stream.mapDefinition of:<R> Stream<R> map(Function<? super T, ? extends R> mapper)
    2. Optional.mapDefinition of:<U> Optional<U> map(Function<? super T, ? extends U> mapper)
    3. The above two definitions are very similar and Optional can be seen 最多包含一个元素 asStream

1234567891011 @Test public void maptest() {String province = "Guangdong"; String City = "Zhongshan"; optional<address> addressoptional = optional.of (new Address (province, city)); //mapper:address, String //optional<address>-optional<string> optional<string> stringoptional = Addressoptional.map (address::getcity); Asserttrue (stringOptional.isPresent ()); Assertequals (city, Stringoptional.get ());}
FlatMap
    1. Stream.flatMapDefinition of:<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
    2. Optional.flatMapDefinition of:<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper)

123456789101112 @Testpublic void flatmaptest() { String province ="Guangdong";String City ="Zhongshan";optional<address> addressoptional = Optional.of (New Address (province, city));//For mapper T-optional<u>, call Optional.map, generate optional<optional<u>>optional<optional<string>> optionaloptional = addressoptional.map (Address-optional.ofnullable ( Address.getcity ()));//For mapper T-optional<u>, call Optional.map, generate Optional<u>optional<string> stringoptional = addressoptional.flatmap (Address-optional.ofnullable (address.getCity () ); Asserttrue (Stringoptional.ispresent ()); Assertequals (city, Stringoptional.get ());}
Solution Reference
1234567891011121314151617181920212223242526 @Test (expected = unsupportedoperationexception.class)public void dereferencetest() { //Get: Simplest + least secureAddress address = Addressoptional.get (); Assertnotnull (address); Address =null;optional<address> emptyaddressoptional = optional.ofnullable (Address); String defaultvalue ="Unknown";///OrElse: Set default valueAddress elseaddress = Emptyaddressoptional.orelse (New Address (DefaultValue, DefaultValue));Assertequals (DefaultValue, Elseaddress.getprovince ()); Assertequals (DefaultValue, Elseaddress.getcity ());delayed call version of//Orelseget:orelseAddress elsegetaddress = Emptyaddressoptional.orelseget (address::new);Assertnull (Elsegetaddress.getprovince ()); Assertnull (Elsegetaddress.getcity ());///ifpresent: The presence value runs consumer, otherwise no action is madeEmptyaddressoptional.ifpresent (System.out::p rintln);///Orelsethrow: Throws an exception if it does not existEmptyaddressoptional.orelsethrow (unsupportedoperationexception::new);}
Filter
1234 @Test public void filtertest() {asserttrue (addressoptional.filter (Address- Address.getcity (). Contains ("Z")). IsPresent ());}
Base type + Optional
    1. OptionalInt, OptionalLong ,OptionalDouble
    2. Most 只有一个 elements, and there is no StreamInt Stream<Integer> performance advantage like that
    3. Not supported map , flatmap ,filter

Java 8--optional

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.