Skip to content

Instantly share code, notes, and snippets.

@aruld
Created January 11, 2018 03:02
Show Gist options
  • Save aruld/3075df36768a97d3113914ad2d7122c1 to your computer and use it in GitHub Desktop.
Save aruld/3075df36768a97d3113914ad2d7122c1 to your computer and use it in GitHub Desktop.
Local Variable Type Inference Examples
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
public class LocalVariableTypeInferenceTest {
private void processOrder(String order) {
System.out.println(order);
}
public static void main(String[] args) throws Exception {
// local variable use
var test = new LocalVariableTypeInferenceTest();
// infers HashSet<String> vs Set<String> orders = new HashSet<>();
var orders = new HashSet<String>();
// indexed for-loop use
for (var i = 0; i < 5; i++) {
orders.add(UUID.randomUUID().toString());
}
// for-each use
for (var order : orders) {
// process an order
test.processOrder(order);
}
// infers Stream<String>
var stream = orders.stream();
stream.forEachOrdered(test::processOrder);
// try-with-resources use
try (var in = Files.newInputStream(Paths.get("./src/LocalVariableTypeInferenceTest.java")); var reader = new BufferedReader(new InputStreamReader(in))) {
// print the imports
reader.lines().takeWhile(e -> !e.startsWith("public")).forEachOrdered(System.out::println);
} catch (IOException e) {
throw e;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment