90. LVTI and streams

Let's consider the following Stream<Integer> stream:

// explicit type
Stream<Integer> numbers = Stream.of(1, 2, 3, 4, 5);
numbers.filter(t -> t % 2 == 0).forEach(System.out::println);

Using LVTI instead of Stream<Integer> is pretty straightforward. Simply replace Stream<Integer> with var, as follows:

// using var, inferred as Stream<Integer>
var numberStream = Stream.of(1, 2, 3, 4, 5);
numberStream.filter(t -> t % 2 == 0).forEach(System.out::println);

Here is another example:

// explicit types
Stream<String> paths = Files.lines(Path.of("..."));
List<File> files = paths.map(p -> new File(p)).collect(toList());

// using var
// inferred as Stream<String>
var pathStream = Files.lines(Path.of(""));

// inferred as List<File>
var fileList = pathStream.map(p -> new File(p)).collect(toList());

It looks like Java 10, LVTI, Java 8, and the Stream API make a good team.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset