Java_Magazine_NovemberDecember_2018

(singke) #1

42


//java at present/


var postRequest
= HttpRequest.newBuilder()
.uri(URI.create("https://httpbin.org/post"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofFile(
Paths.get("data.json"))
)
.build();

You’ve seen a couple of simple examples that showcase the basic use and principles behind
the new HTTP Client API. There’s a lot more to it, including support for WebSockets as well as
adapters to connect with the reactive stream protocol standardized in Java 9.

Local Variable Syntax for Lambda Parameters
Java 10 introduced local variable type inference, which was discussed earlier in this Java
Magazine article. Local variable type inference enables you to do the following:

var url = new URL("http://iteratorlearning.com");

Some additional examples of the use of var appear in the previous section. Java 11 extends this
syntax to the arguments of lambda parameters. Since Java 8, you can declare a lambda expres-
sion this way:

FilenameFilter xmlTargetFiles
= (dir, fileName) -> fileName.endsWith(".xml")
&& "target".equals(dir.getName());

Here, the types of the two arguments, dir and fileName, are inferred. You don’t need to explic-
itly declare them. The types are inferred to be File and String, respectively.
In Java 11, you can rewrite this lambda expression as follows:
Free download pdf