JavaUtils/Java11.java

163 lines
5.4 KiB
Java
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import java.awt.Point;
import java.io.IOException;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
class Java11 {
public static void main(String[] args) {
////////
// 1. //
////////
// if the resource is referenced by a final or effectively final variable,
// a try-with-resources statement can manage a resource without a new variable being declared:
MyAutoCloseable mac = new MyAutoCloseable();
try (mac) {
// do some stuff with mac
}
////////
// 2. //
////////
// use diamond operator in conjunction with anonymous inner classes
List<Integer> fc = new ArrayList<>(1) {}; // anonymous inner class
List<? extends Integer> fc0 = new ArrayList<>(1) {
// anonymous inner class
};
List<?> fc1 = new ArrayList<>(1) {}; // anonymous inner class
////////
// 4. //
////////
// Local Variable Type Inference
var message = "Hello, Java 10";
var point = new Point(1, 2);
////////
// 5. //
////////
// immutable Collections/ Maps
Map<String, Integer> meineMap = Map.of();
Set<String> meinSet = Set.of("key1", "key2", "key3");
List<String> meineListe = List.copyOf(meinSet);
////////
// 6. //
////////
// Optional to Stream Optional.stream() gives us an easy way to you use the power of Streams on Optional elements
List<String> filteredList = new ArrayList<Optional<String>>().stream()
.flatMap(Optional::stream)
.collect(Collectors.toList());
////////
// 7. //
////////
// Collectors get additional methods to collect a Stream into unmodifiable List, Map or Set:
List<Integer> evenList = new ArrayList<Integer>().stream()
.filter(i -> i % 2 == 0)
.collect(Collectors.toUnmodifiableList());
////////
// 8. //
////////
// Optional got a new method orElseThrow() which doesnt take any argument and throws NoSuchElementException if no value is present:
Integer firstEven = List.of(1, 2, 3).stream()
.filter(i -> i % 2 == 0)
.findFirst()
.orElseThrow();
////////
// 9. //
////////
// Java 11 adds a few new methods to the String class
var multilineString = "Baeldung helps \n \n developers \n explore Java.";
List<String> lines = multilineString.lines().collect(Collectors.toList());
assert " ".isBlank();
assert " x ".strip().equals("x");
assert " x ".stripLeading().equals("x ");
assert " x ".stripTrailing().equals(" x");
assert "x".repeat(5).equals("xxxxx");
/////////
// 10. //
/////////
// We can use the new readString and writeString static methods from the Files class:
String fileContent = null;
try {
Path filePath = Files.writeString(Files.createTempFile("demo", ".txt"), "Sample text");
fileContent = Files.readString(filePath);
} catch (IOException ioe) {}
assert fileContent.equals("Sample text");
/////////
// 11. //
/////////
// The java.util.Collection interface contains a new default toArray method which takes an IntFunction argument.
List<String> sampleList = List.of("Java", "Kotlin");
String[] sampleArray = sampleList.toArray(String[]::new);
/////////
// 12. //
/////////
// A static not method has been added to the Predicate interface.
sampleList = List.of("Java", "\n \n", "Kotlin", " ");
List<String> withoutBlanks = sampleList.stream()
.filter(Predicate.not(String::isBlank))
.collect(Collectors.toList());
// While not(isBlank) reads more naturally than isBlank.negate(), the big advantage is that we can also use not with method references,
// like not(String::isBlank).
/////////
// 13. //
/////////
// Support for using the local variable syntax (var keyword) in lambda parameters was added in Java 11.
// We can make use of this feature to apply modifiers to our local variables, like defining a type annotation:
sampleList = List.of("Java", "Kotlin");
String resultString = sampleList.stream()
.map((@Nonnull var x) -> x.toUpperCase())
.collect(Collectors.joining(", "));
assert resultString.equals("JAVA, KOTLIN");
}
}
class MyAutoCloseable implements AutoCloseable {
public void close() {}
}
////////
// 3. //
////////
// Interfaces in the upcoming JVM version can have private methods, which can be used to split lengthy default methods
interface InterfaceWithPrivateMethods {
private static String staticPrivate() {
return "static private";
}
private String instancePrivate() {
return "instance private";
}
default void check() {
String result = staticPrivate();
InterfaceWithPrivateMethods pvt = new InterfaceWithPrivateMethods() {
// anonymous class
};
result = pvt.instancePrivate();
}
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Nonnull {}