Java 8 introduced two powerful features in interfaces:
-
Default Methods – These are methods defined in an interface with a body (implementation). They allow you to add new methods to interfaces without breaking the existing implementation classes.
-
Static Methods – These are utility methods that belong to the interface itself, not to instances.
Both of these are widely used in the Java Collections Framework to provide enhanced capabilities.
Default Methods in Collection Interfaces
Default methods are implemented directly in the interfaces like Iterable
, Collection
, List
, Set
, etc. These allow developers to use built-in behaviors without the need for implementation in custom classes.
Example 1: Using removeIf()
(a default method in Collection
)
List<String> students = new ArrayList<>();
students.add("LotusJavaPrince");
students.add("Mahesh");
students.add("Datta");
students.add("Ganesh");
// Remove names starting with 'D'
students.removeIf(name -> name.startsWith("D"));
// default method from Collection interface
System.out.println(students);
// Output: [LotusJavaPrince, Mahesh, Ganesh]
Code language: JavaScript (javascript)
Example 2: Using forEach()
(from Iterable
interface)
students.forEach(name -> System.out.println("Hello " + name));
// Prints each name with a greeting
Code language: PHP (php)
Static Methods in Collection Interfaces
Static methods are used to provide utility or factory methods. Starting from Java 9, interfaces like List
, Set
, and Map
provide static methods such as of()
, which are used to create immutable instances quickly.
Example 1: Using List.of() (a static method in interface)
students.forEach(name -> System.out.println("Hello " + name));
// Prints each name with a greeting
Code language: PHP (php)
Why Are These Important?
-
Default methods ensure backward compatibility while extending functionality (like adding
forEach()
orremoveIf()
). -
Static methods provide built-in ways to easily create and manage collections without relying on external utility classes.
This makes the Java Collections Framework more functional, concise, and powerful, especially in modern Java programming.