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 (
varkeyword)- 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
Streammethods - New
OptionalmethodsOptional#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 anOptionalwith the result of the supplied lambda, if the originalOptionalis empty, otherwise anOptionalwith the original valueOptional#stream(...)-> CreatesStreamcontaining the value of theOptionalif present, otherwise an emptyStreamOptional#isEmpty()
- New
StringmethodsString#isBlank()String#lines()-> Splits theStringinto anStreamof 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
FilesmethodsFiles.readString(...)-> Reads all file contens as UTF-8 into a StringFiles.writeString(...)-> Writes a String into a file
- New
Matchermethods (RegEx)Matcher#appendReplacement(...)-> Can now also be used withStringBuilderinstead ofStringBufferMatcher#appendTail(...)-> Can now also be used withStringBuilderinstead ofStringBufferMatcher#replaceAll(...)-> TheStringcan now be supplied with a FunctionMatcher#replaceFirst(...)-> TheStringcan now be supplied with a FunctionMatcher#results(...)-> Returns a stream of the match results
- New
CompletableFuturemethods @Deprecatedgets 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.”