Java 8 new features

Java 8 Programming Language Enhancements

Java 8 provides following features for Java Programming:

  • Lambda expressions,
  • Method references,
  • Functional interfaces,
  • Stream API,
  • Default methods,
  • Base64 Encode Decode,
  • Static methods in interface,
  • Optional class,
  • Collectors class,
  • ForEach() method,
  • Nashorn JavaScript Engine,
  • Parallel Array Sorting,
  • Type and Repating Annotations,
  • IO Enhancements,
  • Concurrency Enhancements,
  • JDBC Enhancements etc.

Lambda Expressions

Lambda expression helps us to write our code in functional style. It provides a clear and concise way to implement SAM interface (Single Abstract Method) by using an expression. It is very useful in collection library in which it helps to iterate, filter and extract data.

For more information and examples: click here

Syntax

The basic syntax of a lambda expression is:

  1. (argument-list) -> {body}  
  • argument-list: It can be empty or non-empty as well. It represents the parameters used by the expression.
  • arrow-token (->): It links the arguments to the body of the expression.
  • body: It contains expressions and statements for the lambda expression.

Filename: LambdaExample.java

  1. import java.util.Arrays;  
  2. import java.util.List;  
  3. import java.util.function.Predicate;  
  4. public class LambdaExample {  
  5.     public static void main(String[] args) {  
  6.         List<String> languages = Arrays.asList(“Java”, “Python”, “JavaScript”, “C++”);  
  7.         System.out.println(“Languages which starts with ‘J’:”);  
  8.         filter(languages, (str) -> str.startsWith(“J”));  
  9.     }  
  10.     public static void filter(List<String> names, Predicate<String> condition) {  
  11.         for(String name: names)  {  
  12.             if(condition.test(name)) {  
  13.                 System.out.println(name + ” “);  
  14.             }  
  15.         }  
  16.     }  
  17. }  

Output:

Languages which starts with 'J':
Java
JavaScript

Method References

Java 8 Method reference is used to refer method of functional interface. It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method, we can replace our lambda expression with method reference.

For more information and examples: click here

Types of Method References

There are four main types of method references in Java:

1. Static Method References: They reference methods that are static within classes.

Syntax:

  1. ClassName::staticMethodName  

Example: Math::max references the max method of the Math class.

2. Instance Method References of a Particular Object: They reference methods of a specific instance of a class.

Syntax:

  1. instance::instanceMethodName  

Example: Suppose str is an instance of String, str::length references the length method of str.

3. Instance Method References of an Arbitrary Object of a Particular Type: They reference methods of an instance that will be supplied at the time of calling.

Syntax:

  1. ClassName::methodName  

Example: String::toLowerCase references the toLowerCase method on an instance of String that will be determined at runtime.

4. Constructor References: They reference constructors of classes.

Syntax:

  1. ClassName::new  

Example: ArrayList::new references the constructor of ArrayList.

Filename: MethodReferenceExample.java

  1. import java.util.ArrayList;  
  2. import java.util.Arrays;  
  3. import java.util.List;  
  4. import java.util.function.Function;  
  5. import java.util.function.Supplier;  
  6. import java.util.stream.Collectors;  
  7. public class MethodReferenceExample {  
  8.     public static void main(String[] args) {  
  9.         List<String> words = Arrays.asList(“Java”, “Stream”, “Method”, “References”);  
  10.         // Static Method Reference: Converting all strings to uppercase  
  11.         List<String> upperCaseWords = words.stream()  
  12.                                            .map(String::toUpperCase) // static method reference  
  13.                                            .collect(Collectors.toList());  
  14.         System.out.println(“Uppercase Words: ” + upperCaseWords);  
  15.         // Instance Method Reference of an Arbitrary Object of a Particular Type  
  16.         System.out.println(“Printing each word:”);  
  17.         words.forEach(System.out::println); // instance method reference  
  18.         // Constructor Reference: Creating new instances  
  19.         Supplier<List<String>> listSupplier = ArrayList::new// constructor reference  
  20.         List<String> newList = listSupplier.get();  
  21.         newList.addAll(words);  
  22.         System.out.println(“New List: ” + newList);  
  23.         // Additional Example: Using Function Interface for Constructor Reference  
  24.         Function<String, Integer> stringToInteger = Integer::new// constructor reference  
  25.         Integer number = stringToInteger.apply(“100”);  
  26.         System.out.println(“String to Integer: ” + number);  
  27.     }  
  28. }  

Output:

Uppercase Words: [JAVA, STREAM, METHOD, REFERENCES]
Printing each word:Java
Stream
Method
References
New List: [Java, Stream, Method, References]
String to Integer: 100

Functional Interface

An Interface that contains only one abstract method is known as functional interface. It can have any number of default and static methods. It can also declare methods of object class.

Functional interfaces are also known as Single Abstract Method Interfaces (SAM Interfaces).

For more information and examples: click here

Filename: FunctionalInterfaceExample.java

  1. @FunctionalInterface  
  2. interface Converter<F, T> {  
  3.     T convert(F from);  
  4. }  
  5. public class FunctionalInterfaceExample {  
  6.     public static void main(String[] args) {  
  7.         // Using the Converter functional interface with a lambda expression  
  8.         Converter<String, Integer> stringToInteger = Integer::valueOf;  
  9.         // Applying the converter to convert a string to an integer  
  10.         int convertedValue = stringToInteger.convert(“123”);  
  11.         System.out.println(“Converted Value: ” + convertedValue);  
  12.         // Another example, converting case of a string  
  13.         Converter<String, String> upperCaseConverter = String::toUpperCase;  
  14.         String convertedString = upperCaseConverter.convert(“java”);  
  15.         System.out.println(“Converted String: ” + convertedString);  
  16.     }  
  17. }  

Output:

Converted Value: 123
Converted String: JAVA

Optional

Java introduced a new class Optional in Java 8. It is a public final class which is used to deal with NullPointerException in Java application. We must import java.util package to use this class. It provides methods to check the presence of value for particular variable.

For more information and examples: click here

Filename: OptionalMain.java

  1. import java.util.Optional;  
  2. public class OptionalMain {  
  3.     public static void main(String[] args) {  
  4.         String[] str = new String[10]; // Initialize an array of strings with default null values.  
  5.         str[5] = “Hello, Optional!”; // Uncomment this line to test with a non-null value.  
  6.         // Create an Optional object from the value of str[5].  
  7.         Optional<String> checkNull = Optional.ofNullable(str[5]);  
  8.         // Check if the Optional object contains a value.  
  9.         if (checkNull.isPresent()) {  
  10.             // Convert the string to lowercase if it’s not null.  
  11.             String word = str[5].toLowerCase();  
  12.             System.out.println(word); // Print the lowercase string.  
  13.         } else {  
  14.             System.out.println(“string is null”); // Indicate that the string is null.  
  15.         }  
  16.     }  
  17. }  

Output:

hello, optional!

forEach

Java provides a new method forEach() to iterate the elements. It is defined in Iterable and Stream interfaces.

It is a default method defined in the Iterable interface. Collection classes which extends Iterable interface can use forEach() method to iterate elements.

This method takes a single parameter which is a functional interface. So, you can pass lambda expression as an argument.

For more information and examples: click here

Filename: ForEachMapExample.java

  1. import java.util.Map;  
  2. import java.util.HashMap;  
  3. public class ForEachMapExample {  
  4.     public static void main(String[] args) {  
  5.         // Create a map of Integer keys and String values  
  6.         Map<Integer, String> map = new HashMap<>();  
  7.         map.put(1, “One”);  
  8.         map.put(2, “Two”);  
  9.         map.put(3, “Three”);  
  10.         map.put(4, “Four”);  
  11.         // Use forEach to iterate over the map and print each key-value pair  
  12.         map.forEach((key, value) -> System.out.println(“Key: ” + key + “, Value: ” + value));  
  13.     }  
  14. }  

Output:

Key: 1, Value: One
Key: 2, Value: Two
Key: 3, Value: Three
Key: 4, Value: Four

Date/Time API

Java has introduced a new Date and Time API since Java 8. The java.time package contains Java 8 Date and Time classes.

For more information and examples: click here

API Specification

  • java.time: Core classes for dates, times, combined date and time, instants, durations, periods, and clocks using the ISO-8601 system.
  • java.time.chrono: Supports non-ISO calendar systems with predefined and custom chronologies.
  • java.time.format: For formatting and parsing date-time objects.
  • java.time.temporal: Advanced features for date-time manipulation, aimed at library developers.
  • java.time.zone: Handles time zones, offsets, and rules.

Filename: DateTimeApiShortExample.java

  1. import java.time.LocalDate;  
  2. import java.time.format.DateTimeFormatter;  
  3. public class DateTimeApiShortExample {  
  4.     public static void main(String[] args) {  
  5.         // Current Date  
  6.         LocalDate today = LocalDate.now();  
  7.         System.out.println(“Today: ” + today);  
  8.         // Adding 5 days  
  9.         LocalDate futureDate = today.plusDays(5);  
  10.         System.out.println(“Future Date: ” + futureDate);  
  11.         // Formatting the future date  
  12.         DateTimeFormatter formatter = DateTimeFormatter.ofPattern(“dd-MM-yyyy”);  
  13.         String formattedDate = futureDate.format(formatter);  
  14.         System.out.println(“Formatted Future Date: ” + formattedDate);  
  15.         // Parsing a date string  
  16.         String dateString = “25-12-2024”;  
  17.         LocalDate parsedDate = LocalDate.parse(dateString, formatter);  
  18.         System.out.println(“Parsed Date: ” + parsedDate);  
  19.     }  
  20. }  

Output:

Today: 2024-02-13
Future Date: 2024-02-18
Formatted Future Date: 18-02-2024
Parsed Date: 2024-12-25

Static Method in Interface in Java

Static methods in interfaces are similar to static methods in classes. They are defined with the static keyword and can be called without an instance of the class that implements the interface. These methods are part of the interface and not the objects that implement the interface. Thus, they provide a convenient place for utility methods related to the interface.

Filename: ActionExecutor.java

  1. // Define an interface for displaying messages.  
  2. interface MessageDisplay {  
  3.     // Static method to display a static greeting message.  
  4.     static void showStaticMessage() {  
  5.         // Print a static greeting message to the console.  
  6.         System.out.println(“Static Greeting: Welcome!”);  
  7.     }  
  8.     // Abstract method to be implemented by classes for executing a custom action with a string input.  
  9.     void executeCustomAction(String input);  
  10. }  
  11. // Class that implements the MessageDisplay interface to execute actions.  
  12. public class ActionExecutor implements MessageDisplay {  
  13.     // Main method – the entry point of the program.  
  14.     public static void main(String[] args) {  
  15.         // Create an instance of the ActionExecutor class.  
  16.         ActionExecutor executor = new ActionExecutor();  
  17.         // Call the static method from the MessageDisplay interface to show the static message.  
  18.         MessageDisplay.showStaticMessage();  
  19.         // Call the implemented abstract method with a custom message.  
  20.         executor.executeCustomAction(“Overridden Message: Action Completed.”);  
  21.     }  
  22.     // Implementation of the abstract method from the MessageDisplay interface.  
  23.     @Override  
  24.     public void executeCustomAction(String inputData) {  
  25.         // Print the input data to the console.  
  26.         System.out.println(inputData);  
  27.     }  
  28. }  

Output:

Static Greeting: Welcome!
Overridden Message: Action Completed.

IO Enhancements

Java 8 introduced several enhancements to the Input/Output (IO) and New Input/Output (NIO) frameworks, focusing primarily on improving the ease of use and efficiency of file and stream handling. These enhancements are part of the java.nio package and include the following notable features:

Stream API Enhancements for IO

  • list(Path dir): This method returns a lazily filled stream of Path objects, where each element represents a directory entry in the specified directory (dir).
  • lines(Path path): This method reads all lines from a file specified by the path parameter and returns them as a Stream<String>. Each element of the stream represents a line of text from the file.
  • find(): This method is used to search for files in the file tree rooted at a provided starting file. It returns a stream filled with Path objects representing the files found during the search. However, you haven’t provided the complete method signature, so it’s unclear how this method is used.
  • lines(): This method returns a stream containing all of the lines from the BufferedReader’s input source. Each element of the stream represents a line of text from the input source. This method is useful for processing text data in a file or from any other input source.

Type and Repeating Annotations

Type Annotations

Type Annotations augment Java’s type system by allowing annotations to be used in any context where a type is used. This enhancement enables developers to convey more information to the compiler, aiding in error detection and prevention at compile time. For example, to safeguard against NullPointerException, a variable declaration can be annotated to ensure that it never holds a null value:

  1. @NonNull String str;  

Further examples of Type Annotations include:

Ensuring a list does not contain null elements:

  1. @NonNull List<String>  

Specifying that elements of a list must not be null:

  1. List<@NonNull String> str  

Declaring that an array should only contain non-negative integers:

  1. Arrays<@NonNegative Integer> sort  

Marking a file as encrypted for security purposes:

  1. @Encrypted File file  

Indicating that a connection is open and should be managed accordingly:

  1. @Open Connection connection  

Specifying an exception thrown under a particular condition, such as division by zero:

  1. void divideInteger(int a, int b) throws @ZeroDivisor ArithmeticException  

Repeating Annotations

Java 8 introduced the concept of Repeating Annotations, allowing you to apply the same annotation multiple times to a single element in your code. This feature is particularly useful for situations where you need to repeatedly annotate an element with the same annotation to convey multiple pieces of information or apply multiple settings.

To use Repeating Annotations, Java requires two key pieces:

1. Declare a Repeatable Annotation Type:

First, we declare the @Review annotation and mark it as repeatable using the @Repeatable meta-annotation. The value of @Repeatable is set to the container annotation type, which in this case is Reviews.

  1. import java.lang.annotation.Repeatable;  
  2. import java.lang.annotation.Retention;  
  3. import java.lang.annotation.RetentionPolicy;  
  4. @Repeatable(Reviews.class)  
  5. @Retention(RetentionPolicy.RUNTIME) // Make this annotation available at runtime.  
  6. @interface Review {  
  7.     String reviewer();  
  8.     String date();  
  9.     String comment();  
  10. }  

In this example, @Review annotations can include the reviewer’s name, the date of the review, and a comment.

2. Declare the Containing Annotation Type:

We define the Reviews container annotation. It must have a value element that returns an array of the repeatable annotation type (Review[]). This container is used to hold all the @Review annotations applied to the same element.

  1. @Retention(RetentionPolicy.RUNTIME) // Make this annotation available at runtime.  
  2. @interface Reviews {  
  3.     Review[] value();  
  4. }  

Filename: EmployeeRoles.java

  1. import java.lang.annotation.ElementType;  
  2. import java.lang.annotation.Retention;  
  3. import java.lang.annotation.RetentionPolicy;  
  4. import java.lang.annotation.Target;  
  5. import java.lang.annotation.Repeatable;  
  6. // Define the repeatable annotation type  
  7. @Retention(RetentionPolicy.RUNTIME)  
  8. @Target(ElementType.TYPE) // Apply to class level  
  9. @Repeatable(Roles.class)  
  10. @interface Role {  
  11.     String value();  
  12. }  
  13.   
  14. // Define the container annotation for the repeatable annotation  
  15. @Retention(RetentionPolicy.RUNTIME)  
  16. @Target(ElementType.TYPE) // Apply to class level  
  17. @interface Roles {  
  18.     Role[] value();  
  19. }  
  20.   
  21. // Use the repeating annotation on a class  
  22. @Role(“Developer”)  
  23. @Role(“Lead”)  
  24. @Role(“Manager”)  
  25. public class EmployeeRoles {  
  26.     public static void main(String[] args) throws NoSuchMethodException {  
  27.         // Access and print the repeated annotations  
  28.         if (EmployeeRoles.class.isAnnotationPresent(Roles.class)) {  
  29.             Roles rolesAnnotation = EmployeeRoles.class.getAnnotation(Roles.class);  
  30.             for (Role role : rolesAnnotation.value()) {  
  31.                 System.out.println(“Role: ” + role.value());  
  32.             }  
  33.         } else {  
  34.             System.out.println(“No Roles Annotation present.”);  
  35.         }  
  36.     }  
  37. }  

Output:

Role: Developer
Role: Lead
Role: Manager

Default Methods

Java provides a facility to create default methods inside the interface. Methods which are defined inside the interface and tagged with default keyword are known as default methods. These methods are non-abstract methods and can have method body.

For more information and examples: click here

Filename: DefaultMethodsExample.java

  1. interface Vehicle {  
  2.     // Abstract method  
  3.     String getBrand();  
  4.     // Default method  
  5.     default void turnAlarmOn() {  
  6.         System.out.println(“The vehicle alarm is now on.”);  
  7.     }  
  8.     // Another default method  
  9.     default void turnAlarmOff() {  
  10.         System.out.println(“The vehicle alarm is now off.”);  
  11.     }  
  12. }  
  13. class Car implements Vehicle {  
  14.     private String brand;  
  15.     Car(String brand) {  
  16.         this.brand = brand;  
  17.     }  
  18.     @Override  
  19.     public String getBrand() {  
  20.         return brand;  
  21.     }  
  22.     // The class can choose to override a default method  
  23.     @Override  
  24.     public void turnAlarmOn() {  
  25.         System.out.println(“The car alarm is now on.”);  
  26.     }  
  27. }  
  28. public class DefaultMethodsExample {  
  29.     public static void main(String[] args) {  
  30.         Vehicle myCar = new Car(“Tesla”);  
  31.         System.out.println(“Brand: ” + myCar.getBrand());  
  32.         myCar.turnAlarmOn(); // Overridden method  
  33.         myCar.turnAlarmOff(); // Inherited default method  
  34.     }  
  35. }  

Output:

Brand: Tesla
The car alarm is now on.
The vehicle alarm is now off.

Nashorn JavaScript Engine

Nashorn JavaScript Engine

Nashorn is a JavaScript engine. It is used to execute JavaScript code dynamically at JVM (Java Virtual Machine). Java provides a command-line tool jjs that is used to execute JavaScript code.

We can execute JavaScript code by two ways:

  1. By Using jjs command-line tool, and
  2. By embedding into Java source code.

StringJoiner

Java added a new final class StringJoiner in java.util package. It is used to construct a sequence of characters separated by a delimiter. Now, we can create string by passing delimiters like comma(,), hyphen(-) etc.

For more information and examples: click here

Filename: StringJoinerExample.java

  1. import java.util.StringJoiner;  
  2. public class StringJoinerExample {  
  3.     public static void main(String[] args) {  
  4.         // Create a StringJoiner with a delimiter, prefix, and suffix  
  5.         StringJoiner joiner = new StringJoiner(“, “, “[“, “]”);  
  6.         // Add strings to the StringJoiner  
  7.         joiner.add(“Apple”);  
  8.         joiner.add(“Banana”);  
  9.         joiner.add(“Cherry”);  
  10.         joiner.add(“Date”);  
  11.         // Convert the StringJoiner to String and print the result  
  12.         String result = joiner.toString();  
  13.         System.out.println(result);  
  14.     }  
  15. }  

Output:

[Apple, Banana, Cherry, Date]

Collectors

Collectors is a final class that extends Object class. It provides reduction operations, such as accumulating elements into collections, summarizing elements according to various criteria etc.

For more information and examples: click here

Filaname: CollectorsExample.java

  1. import java.util.Arrays;  
  2. import java.util.List;  
  3. import java.util.Map;  
  4. import java.util.stream.Collectors;  
  5. public class CollectorsExample {  
  6.     public static void main(String[] args) {  
  7.         // Example list of people’s names  
  8.         List<String> names = Arrays.asList(“John”, “Sara”, “Mark”, “Sara”, “Chris”, “Paula”);  
  9.         // Collecting into a List  
  10.         List<String> nameList = names.stream().collect(Collectors.toList());  
  11.         System.out.println(“Names List: ” + nameList);  
  12.         // Grouping names by the first letter  
  13.         Map<Character, List<String>> namesByFirstLetter = names.stream()  
  14.             .collect(Collectors.groupingBy(name -> name.charAt(0)));  
  15.         System.out.println(“Names Grouped by First Letter: ” + namesByFirstLetter);  
  16.         // Joining names into a single string separated by commas  
  17.         String allNames = names.stream().collect(Collectors.joining(“, “));  
  18.         System.out.println(“All Names Joined: ” + allNames);  
  19.         // Counting the distinct names  
  20.         long distinctNameCount = names.stream().distinct().count();  
  21.         System.out.println(“Distinct Names Count: ” + distinctNameCount);  
  22.     }  
  23. }  

Output:

Names List: [John, Sara, Mark, Sara, Chris, Paula]
Names Grouped by First Letter: {J=[John], S=[Sara, Sara], M=[Mark], C=[Chris], P=[Paula]}
All Names Joined: John, Sara, Mark, Sara, Chris, Paula
Distinct Names Count: 5

Stream API

Java 8 java.util.stream package consists of classes, interfaces and an enum to allow functional-style operations on the elements. It performs lazy computation. So, it executes only when it requires.

For more information and examples: click here

Filename: StreamApiExample.java

  1. import java.util.Arrays;  
  2. import java.util.List;  
  3. import java.util.stream.Collectors;  
  4.   
  5. public class StreamApiExample {  
  6.     public static void main(String[] args) {  
  7.         // A list of integers  
  8.         List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);  
  9.   
  10.         // Use Stream API to filter, map, and collect operations  
  11.         List<Integer> evenSquares = numbers.stream()  
  12.                                            .filter(n -> n % 2 == 0) // Filter even numbers  
  13.                                            .map(n -> n * n) // Map to their squares  
  14.                                            .collect(Collectors.toList()); // Collect results into a list  
  15.   
  16.         // Print the resulting list  
  17.         System.out.println(evenSquares);  
  18.     }  
  19. }  

Output:

[4, 16, 36, 64, 100]

Stream Filter

Java stream provides a method filter() to filter stream elements on the basis of given predicate. Suppose, you want to get only even elements of your list, you can do this easily with the help of filter() method.

This method takes predicate as an argument and returns a stream of resulted elements.

For more information and examples: click here

Syntax:

The filter method accepts a Predicate<T> as its argument. A Predicate<T> is a functional interface specifying a single boolean-valued method with one argument of type T.

  1. Stream<T> filter(Predicate<? super T> predicate)  

Filename: StreamFilterExample.java

  1. import java.util.Arrays;  
  2. import java.util.List;  
  3. import java.util.stream.Collectors;  
  4. public class StreamFilterExample {  
  5.     public static void main(String[] args) {  
  6.         // A list of names  
  7.         List<String> names = Arrays.asList(“John”, “Sara”, “Mark”, “Jennifer”, “Paul”, “Jane”);  
  8.         // Use Stream API to filter names that start with “J”  
  9.         List<String> namesStartingWithJ = names.stream()  
  10.                                                .filter(name -> name.startsWith(“J”)) // Filter names starting with “J”  
  11.                                                .collect(Collectors.toList()); // Collect results into a list  
  12.         // Print the filtered list  
  13.         System.out.println(namesStartingWithJ);  
  14.     }  
  15. }  

Output:

[John, Jennifer, Jane]

Java Base64 Encoding and Decoding

Java provides a class Base64 to deal with encryption and decryption. You need to import java.util.Base64 class in your source file to use its methods.

This class provides three different encoders and decoders to encrypt information at each level.

For more information and examples: click here

Filename: Base64Example.java

  1. import java.util.Base64;  
  2. public class Base64Example {  
  3.     public static void main(String[] args) {  
  4.         // Original String  
  5.         String originalString = “Hello, World!”;  
  6.         // Encode using basic encoder  
  7.         String encodedString = Base64.getEncoder().encodeToString(originalString.getBytes());  
  8.         System.out.println(“Encoded String (Basic) : ” + encodedString);  
  9.         // Decode the base64 encoded string  
  10.         byte[] decodedBytes = Base64.getDecoder().decode(encodedString);  
  11.         String decodedString = new String(decodedBytes);  
  12.         System.out.println(“Decoded String : ” + decodedString);  
  13.         // URL and Filename safe encoding  
  14.         String urlEncodedString = Base64.getUrlEncoder().encodeToString(originalString.getBytes());  
  15.         System.out.println(“Encoded String (URL) : ” + urlEncodedString);  
  16.         // MIME encoder example  
  17.         String mimeEncodedString = Base64.getMimeEncoder().encodeToString(originalString.getBytes());  
  18.         System.out.println(“Encoded String (MIME) : ” + mimeEncodedString);  
  19.     }  
  20. }  

Output:

Encoded String (Basic) : SGVsbG8sIFdvcmxkIQ==
Decoded String : Hello, World!
Encoded String (URL) : SGVsbG8sIFdvcmxkIQ==
Encoded String (MIME) : SGVsbG8sIFdvcmxkIQ==

Java Parallel Array Sorting

Java provides a new additional feature in Arrays class which is used to sort array elements parallelly. The parallelSort() method has added to java.util.Arrays class that uses the JSR 166 Fork/Join parallelism common pool to provide sorting of arrays. It is an overloaded method.

For more information and examples: click here

Filename: ParallelArraySortingExample.java

  1. import java.util.Arrays;  
  2. import java.util.Comparator;  
  3. public class ParallelArraySortingExample {  
  4.     public static void main(String[] args) {  
  5.         // Parallel sorting for an array of primitives  
  6.         int[] numbers = {9, 3, 1, 5, 13, 12, 7, 4, 11, 6};  
  7.         System.out.println(“Original array: ” + Arrays.toString(numbers));  
  8.         Arrays.parallelSort(numbers);  
  9.         System.out.println(“Sorted array: ” + Arrays.toString(numbers));  
  10.         // Parallel sorting for an array of objects with a custom comparator  
  11.         String[] fruits = {“Peach”, “Apple”, “Orange”, “Banana”, “Grape”, “Pear”};  
  12.         System.out.println(“\nOriginal array: ” + Arrays.toString(fruits));  
  13.         // Using a lambda expression for the comparator to sort in reverse alphabetical order  
  14.         Arrays.parallelSort(fruits, Comparator.reverseOrder());  
  15.         System.out.println(“Sorted array in reverse order: ” + Arrays.toString(fruits));  
  16.     }  
  17. }  

Output:

Original array: [9, 3, 1, 5, 13, 12, 7, 4, 11, 6]
Sorted array: [1, 3, 4, 5, 6, 7, 9, 11, 12, 13]
Original array: [Peach, Apple, Orange, Banana, Grape, Pear]
Sorted array in reverse order: [Pear, Peach, Orange, Grape, Banana, Apple]

2 thoughts on “Java 8 new features”

  1. Hey very nice site!! Man .. Beautiful .. Amazing .. I’ll bookmark your blog and take the feeds also厈I am happy to find a lot of useful info here in the post, we need work out more strategies in this regard, thanks for sharing. . . . . .

  2. An fascinating dialogue is worth comment. I think that you must write extra on this matter, it may not be a taboo topic but generally persons are not enough to speak on such topics. To the next. Cheers

Comments are closed.