Java 8 to Java 11 - What are the new language features?
When you think about upgrading to Java 11 from Java 8 (e.g. from one LTS to the next), you might wonder about the new language features the new version provides. So here you find a list of all language features, which were added in Java 9, 10 and 11.
- Private methods in interfaces
- Since we can use static and default methods in interfaces, it is sometimes useful to structure this code in private methods
- Local variable type inference (
var
keyword)- Can be used to add annotations to lambdas
- Factory methods for immutable collections
List.of();
-> creates an empty ListList.of("one", "two", "three");
Map.of(1, "one", 2, "two", 3, "three");
- New
Stream
methods - New
Optional
methodsOptional#orElseThrow()
(no parameters) -> Does the same asOptional#get()
, but the method name better describes, what happens, if no value is present.Optional#ifPresentOrElse(...)
-> Does the same asOptional#ifPresent
, but you can define an action, if the value is not presentOptional#or(...)
-> Returns anOptional
with the result of the supplied lambda, if the originalOptional
is empty, otherwise anOptional
with the original valueOptional#stream(...)
-> CreatesStream
containing the value of theOptional
if present, otherwise an emptyStream
Optional#isEmpty()
- New
String
methodsString#isBlank()
String#lines()
-> Splits theString
into anStream
of Strings, separated by line breaksString#repeat(int n)
String#strip()
-> Removes all UTF-8 whitespace from the beginning and end of the StringString#stripLeading()
String#stripTrailing()
- New
Files
methodsFiles.readString(...)
-> Reads all file contens as UTF-8 into a StringFiles.writeString(...)
-> Writes a String into a file
- New
Matcher
methods (RegEx)Matcher#appendReplacement(...)
-> Can now also be used withStringBuilder
instead ofStringBuffer
Matcher#appendTail(...)
-> Can now also be used withStringBuilder
instead ofStringBuffer
Matcher#replaceAll(...)
-> TheString
can now be supplied with a FunctionMatcher#replaceFirst(...)
-> TheString
can now be supplied with a FunctionMatcher#results(...)
-> Returns a stream of the match results
- New
CompletableFuture
methods @Deprecated
gets two new parametersboolean forRemoval
-> “Indicates whether the annotated element is subject to removal in a future version.”String since
-> “The version in which the annotated element became deprecated.”