Java 8 Features
- Interface Default and Static Methods
- Method References
- Functional Interfaces and Lambda Expressions
- Java Stream API for Bulk Data Operations on Collections
- Optional Class
- Java Time API
- StringJoiner
- Java Parallel Array Sorting
- forEach() method in Iterable interface
- Collection API improvements
- Concurrency API improvements
- Java IO improvements
- Collectors Class
- Base64 Encoder
Interface Default and Static Methods
interface Example{
static String sayHello() {
System.out.println("Hello");
return "Hello";
}
//can be overridden.
default String sayBye() {
return "bye";
}
}
Method References
Reference to a Static Method
Syntax :- ContainingClass::methodName.
numList.forEach(System.out::println);
Reference to an Instance Method
syntax containingInstance::methodName.
FuncExample x = s::isMarried;//can be any method returns boolean
@FunctionalInterface
interface FuncExample {
boolean isAnything();
}
Reference to an Instance Method of an Object of a Particular Type
syntax ContainingType::methodName.
listStudent.stream().filter(Student::isMarried).collect(Collectors.toList());
Optional
// set an optional empty value. optinal.get() will throw NPE
Optional<String> optional = Optional.empty();
String str = "value";
Optional<String> optiona2 = Optional.of(str);
// if str null will throw NPE only for non null objec
Optional<String> optiona2 = Optional.ofNullable(getString());
// null is allowed
List<String> listOpt = getList().orElseGet(() -> new ArrayList<>());
// if the getList() returns null it will create an empty array
Optional<User> user = Optional.ofNullable(getUser());
String result = user.map(User::getAddress)
.map(Address::getStreet).orElse("Address N/A");
Throwing Custom Exception
String result = valueOpt.orElseThrow(CustomException::new).toUpperCase();
Date/Time API
LocalDateTime dateAndTime = LocalDateTime.now(ZoneId.of("Asia/Kolkata"));
System.out.println(dateAndTime );
LocalTime time = LocalTime.now(ZoneId.of("Asia/Kolkata"));
System.out.println(time);
LocalDate date = LocalDate.now(ZoneId.of("Asia/Kolkata"));
System.out.println(date);
ZonedDateTime date = ZonedDateTime.now();
System.out.println(date);
//2023-02-23T18:59:33.506042900+08:00[Asia/Singapore]
ZonedDateTime zoneDateById = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));
System.out.println(zoneDateById);
//2023-02-23T16:29:33.509040100+05:30[Asia/Kolkata]
OffsetTime date = OffsetTime.now(ZoneId.of("Asia/Kolkata"));
System.out.println(date);
// 16:32:38.897413600+05:30
OffsetDateTime date = OffsetDateTime.now(ZoneId.of("Asia/Kolkata"));
System.out.println(date);
// 2023-02-23T16:33:44.422517600+05:30
StringJoiner joinNames = new StringJoiner(","); // passing comma(,) as delimiter
// Adding values to StringJoiner
joinNames.add("Select name");
joinNames.add("age");
joinNames.add(" from");
StringJoiner tableData = new StringJoiner(" ");
tableData.add("Student");
tableData.add("where");
tableData.add("something;");
joinNames.merge(tableData);
System.out.println(joinNames);
//Select name,age, from,Student where something;
Java Parallel Array Sorting
int[] arr = {20,5,6,3,80,8};
Arrays.parallelSort(arr);
System.out.println(Arrays.toString(arr));
//Suitable for large array sorting
Stream for Arrays Class
int chars[] = new int[10];
int max = Arrays.stream(chars).max().getAsInt();
IO Enhancements
// Files in a directory
Files.list(Path.of("C:\\Users\\Dayalan\\Downloads\\")).forEach(System.out::println);
// File content as stream of strings
Files.lines(Path.of("C:\\Users\\Dayalan\\Downloads\\addresses.csv")).forEach(System.out::println);
// Files.find(startPath,searchDepth,findCondition,followLink-Optional)
List<Path> listOfPath = Files.find(
Path.of("D:\\Entertainment"),
Integer.MAX_VALUE,
(a, b) -> a.getFileName().toString().equals("Rockabye.mp3"))
.collect(Collectors.toList());
listOfPath.forEach(System.out::println); // Ref:
// https://mkyong.com/java/java-files-find-examples/
BufferedReader.lines()
FileReader f = new FileReader("C:\\Users\\Dayalan\\Downloads\\addresses.csv");
BufferedReader bR = new BufferedReader(f);
bR.lines().filter(n -> n.contains("John")).findAny().ifPresent(System.out::println);
Miscellaneous Java 8 Core API improvements
Some miscellaneous API improvements that might come handy are:
- ThreadLocal static method withInitial(Supplier supplier) to create instances easily.
- The Comparator interface has been extended with a lot of default and static methods for natural ordering, reverse order, etc.
- min(), max() and sum() methods in Integer, Long and Double wrapper classes.
- logicalAnd(), logicalOr() and logicalXor() methods in Boolean class.
- ZipFile.stream() method to get an ordered Stream over the ZIP file entries. Entries appear in the Stream in the order they appear in the central directory of the ZIP file.
- Several utility methods in Math class.
- jjs command is added to invoke Nashorn Engine.
- jdeps command is added to analyze class files
- JDBC-ODBC Bridge has been removed.
- PermGen memory space has been removed and MetaSpace introduced
Java 11
- Local-Variable Syntax for Lambda Parameters: The ability to use var in the parameters of a lambda expression, which makes the code more concise.
- HTTP Client API: The new HTTP client API provides a more efficient and flexible way to perform HTTP requests and handle responses.
- Epsilon: A new experimental garbage collector that is designed to handle very short-lived objects, reducing the impact on overall application performance.
- ZGC: A new experimental low-latency garbage collector that is designed for large heaps and that can handle multi-terabyte heaps.
- Flight Recorder: A new tool that allows you to collect detailed information about the behavior of your application, which can help you diagnose issues and optimize performance.
- Dynamic Class-File Constants: A new constant pool form that allows constants to be defined at runtime, enabling improved performance and reducing the memory footprint of some applications.
- Unicode 10: Java 11 includes support for Unicode 10, which adds new characters and scripts, including the bitcoin symbol.
- Enhanced Deprecation: A new @Deprecated annotation that allows developers to indicate when a feature will be removed or become obsolete, and to provide additional information about the deprecation.
- JEP 321: The specification of the Java EE and CORBA modules has been removed, as they are no longer needed in the modern Java ecosystem.
- Other improvements: Java 11 also includes various other improvements, such as better support for dynamic class loading, better performance for string concatenation, and improved startup time for small applications.
Local-Variable Syntax
var list = Arrays.asList(10,2,36,5,4,8);
//Type of list automatically identified based on the right side definition
list.stream().forEach( ( var n)-> System.out.println(n));
Using inside lambda
The () are must, we can skip them,
(var s1) -> s1 + s1;
If we use var for one variable others can not be skipped or mixed with different variable types.
Comments
Post a Comment