Skip to content

Instantly share code, notes, and snippets.

@jon-ruckwood
Last active May 9, 2018 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jon-ruckwood/b5fc16cb826161bd0f852ec794ceb401 to your computer and use it in GitHub Desktop.
Save jon-ruckwood/b5fc16cb826161bd0f852ec794ceb401 to your computer and use it in GitHub Desktop.
Notes on Venkat Subramaniam's Java 9 and Java 10: The Key Parts
// Java 9
// JDK improvements
Stream#takeWhile // `limit` using a predicate, i.e. `break`
Stream#dropWhile // `skip` using a predicate, i.e. `continue`
Stream#iterate // emulate a for-loop with a stream, e.g. (not previously possible)
IntStream.iterate(0, i -> i < 10, i -> i + 2)
.forEach(System.out::println);
Optional#ifPresentOrElse
Optional#or // `orElse` unwraps the value, `or` allows you to supply another Optional
Optional#stream // as a Stream, either empty or single element
Collectors#filtering // e.g.
people.stream()
.collect(groupingBy(Person::getName, filtering(person -> person.getAge() > 20, toList()))))
Collectors#flatMapping // e.g.
people.stream()
.collect(groupingBy(Person::getName, flatMapping(person -> Stream.of(person.getName().split("")), toList()))));
CompletableFuture#completeOnTimeout
CompletableFuture#orTimeout
List#of // Immutable collections + factory methods
Set#of
Map#of
// Anonymous inner class generic type inference
List<Integer> numbers = new ArrayList<> {
{ ^^
add(1);
add(2);
add(3);
}
};
numbers.add(4);
// try-with-resources improvements(?)
try (resource) { // <-- resource must be final or effectively final
// ...
}
resource.foo() // <-- hmm...
// _ is now a keyword
int _ = n // compiler error, `_` will *possibly* be used for pattern matching in a future release.
// Java 10
// Local Type Inference
var numbers = new ArrayList<>()
List<Integer> numbers = new ArrayList<Integer>() // -> List<Integer>
List<Integer> numbers = new ArrayList<>() // -> List<Integer>
var numbers = new ArrayList<Integer>() // -> (Array?)List<Integer>
var numbers = new ArrayList<>() // -> (Array?)List<???>
var numbers = List.of(1, 2, 3) // -> (Array?)List<Integer>
var numbers = List.of(1, 2, 3, "foo") // -> (Array?)List<Object>
var numbers = List.of<Integer>(1, 2, 3, "foo") // -> compile error
/*
Rule of thumb:
- not for people with bad practices, i.e. single char named variable `n`
- don’t use inference on both sides, give context on RHS, otherwise type may be different to what you expect!
- not always an advantage to use
- only use when both you and the compile know the types
- don’t confuse people
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment