preface
Today, I encountered a problem. I received the data returned when calling the third-party interface with the encapsulated object. The returned data fields are code, MSG and data. I use the data in the data directly received by the object. There was a problem judging the data.
1, Return to data display?
There are two types of return: data with data and no data
1.data no data
{"code": "1003", "msg": "the client operating system does not exist", "data": {}
2.data has data but is empty
{"code": "0", "msg": "operation succeeded", "data": {"fileList": [], "count": "0"}}
2, Recurrence of error reporting scenario
//Here, I directly call the third-party interface, and the return value data is received using the subplatform SubPlatformFileResp subPlatform = client.getFilesSubPlatform(subPlatFormFileReq); if(subPlatform.getData()!=null){ //Non null judgment of data if(!subPlatform.getData().getFileList().isEmpty()){ //Business logic } }
It can be seen from the return value that data is {}, but data is not null. Therefore, when getFileList() is obtained later, a null pointer exception will be reported because there is no such object. Of course, this problem can also be solved by judging the filelist as null
if (subPlatform.getData().getFileList()!=null){ }
2, Optional elegant solution
1.java8 provides the optional class for judgment processing and business logic processing after empty judgment
Modified code
if(Optional.ofNullable(subPlatform.getData().getFileList()).isPresent()){ }
2.optional class
of
Create an Optional for a non null value. The of method creates an Optional class through a factory method. It should be noted that the parameters passed in when creating an object cannot be null. If the passed in parameter is null, a NullPointerException is thrown
Optional<String> optional = Optional.of("xiaoming"); //null is passed in and NullPointerException is thrown Optional<Object> o = Optional.of(null);
ofNULLable
Create an option for the specified value. If the specified value is null, an empty option will be returned
Optional<Object> o1 = Optional.ofNullable(null);
isPresent
If the value exists, return true; otherwise, return false
Optional<String> optiona2 = Optional.of("xiaoming"); System.out.println(optiona2.isPresent());
get
Optional returns if there is a value. NoSuchElementException is not thrown
Optional<Object> o1 = Optional.ofNullable(null); System.out.println(o1.get());
ifPresent
Optional<Object> o1 = Optional.ofNullable(null); o1.ifPresent(s -> System.out.println(s));
orElse
If there is a value, it will be returned; otherwise, it will return other specified values
Optional<Object> o1 = Optional.ofNullable(null); System.out.println(o1.orElse("output orElse")); // Output orElse
orElseGet
orElseGet is similar to the orElse method, except that the default value is obtained. The orElse method takes the incoming string as the default value. The orElseGet method can accept the implementation of the Supplier interface to generate the default value
Optional<Object> o1 = Optional.ofNullable(null); System.out.println(o1.orElseGet(() -> "default value")); // default value
orElseThrow
If there is a value, it will be returned; otherwise, an exception created by the supplier interface will be thrown.
Optional<Object> o1 = Optional.ofNullable(null); try { o1.orElseThrow(() -> new Exception("Abnormal!")); } catch (Exception e) { System.out.println("info:" + e.getMessage()); }//Output: info: exception!
map
If there is a value, call the mapping function to get the return value. If the return value is not null, an option containing the mapping return value is created as the return value of the map method; otherwise, an empty option is returned.
Optional<String> optional = Optional.of("xiaoming"); String s = optional.map(e -> e.toUpperCase()).orElse("shiyilingfeng"); System.out.println(s); //Output: XIAOMING
flatMap
If there is a value, execute the mapping function for it to return the return value of Optional type; otherwise, it returns null Optional. Different from map, the return value of flatMap must be Optional, and the return value of map can be any type T
Optional<String> optional = Optional.of("xiaoming"); Optional<String> s = optional.flatMap(e -> Optional.of(e.toUpperCase())); System.out.println(s.get()); //Output: XIAOMING
filter
List<String> strings = Arrays.asList("rmb", "doller", "ou"); for (String s : strings) { Optional<String> o = Optional.of(s).filter(s1 -> !s1.contains("o")); System.out.println(o.orElse("Not included o of")); }//Output: rmb Not included o of Not included o of
summary
Optional is a very useful supplement to java. It aims to reduce NullPointerExceptions in code. Although it cannot be eliminated 100%, it is also carefully designed. Using optional can better help us create applications with strong readability and fewer bug s.reference resources
https://www.toutiao.com/i6872294360059216388?wid=1638863738494