Here are the key points about Collection interface:
- If we want to represent a group of individual objects as a single entity then we should go for collections.
- Collection Interface is considered as the root interface of the Collection Framework.
- Collection Interface defines the most common methods which are applicable for any collection object.
- List, Queue, and Set are all subinterfaces of Collection interface.
- JDK does not provide any direct implementations of this interface. But, JDK provides direct implementations of it’s sub-interfaces.
The following example demonstrates the usage of important Collection interface methods:
package com.java.collections.interfaces;
import java.util.ArrayList;
import java.util.Collection;
public class CollectionDemo {
public static void main(String[] args) {
Collection < String > fruitCollection = new ArrayList < > ();
fruitCollection.add("banana");
fruitCollection.add("apple");
fruitCollection.add("mango");
System.out.println(fruitCollection);
fruitCollection.remove("banana");
System.out.println(fruitCollection);
System.out.println(fruitCollection.contains("apple"));
fruitCollection.forEach((element) - > {
System.out.println(element);
});
fruitCollection.clear();
System.out.println(fruitCollection);
}
}
Output
[banana, apple, mango]
[apple, mango]
true
apple
mango
[]
Free Spring Boot Tutorial - 5 Hours Full Course
Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course