Java 9 Features with Examples
Factory Methods for Immutable List, Set, Map and Map.Entry
Oracle Corp has introduced some convenient factory methods to create Immutable List, Set, Map and Map.Entry objects. These utility methods are used to create empty or non-empty Collection objects.
In Java SE 8 and earlier versions, We can use Collections class utility methods like unmodifiableXXX to create Immutable Collection objects. For instance, if we want to create an Immutable List, then we can use Collections.unmodifiableList method.
However these Collections.unmodifiableXXX methods are very tedious and verbose approach. To overcome those shortcomings, Oracle corp has added couple of utility methods to List, Set and Map interfaces.
List and Set interfaces have “of()” methods to create an empty or no-empty Immutable List or Set objects as shown below:
Empty List Example
List immutableList = List.of();
Non-Empty List Example
List immutableList = List.of("one","two","three");
Map has two set of methods: of() methods and ofEntries() methods to create an Immutable Map object and an Immutable Map.Entry object respectively.
Empty Map Example
jshell> Map emptyImmutableMap = Map.of()
emptyImmutableMap ==> {}
Non-Empty Map Example
jshell> Map nonemptyImmutableMap = Map.of(1, "one", 2, "two", 3, "three")
nonemptyImmutableMap ==> {2=two, 3=three, 1=one}
If you want to read more about these utility methods, please go through the following links:
- Java 9 Factory Methods for Immutable List
- Java 9 Factory Methods for Immutable Set
- Java 9 Factory Methods for Immutable Map and Map.Entry
Private methods in Interfaces
In Java 8, we can provide method implementation in Interfaces using Default and Static methods. However we cannot create private methods in Interfaces.
To avoid redundant code and more re-usability, Oracle Corp is going to introduce private methods in Java SE 9 Interfaces. From Java SE 9 on-wards, we can write private and private static methods too in an interface using ‘private’ keyword.
These private methods are like other class private methods only, there is no difference between them.
public interface Card{
private Long createCardID(){
// Method implementation goes here.
}
private static void displayCardDetails(){
// Method implementation goes here.
}
}
If you want to read more about this new feature, please go through this link: Java 9 Private methods in Interface.
Comments
Post a Comment