Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.