Java Program that Shows Use of Collection Interface
The Collection framework is a unified architecture for representing and manipulating collections, enabling collections to be manipulated independently of implementation details.
Uses and advantages of Collection Framework:
- This reduces the efforts of programmers by providing data structures and algorithms, so we do not have to write them.
- This increases performance by providing a high-performance implementation of data structures and algorithms.
- This provides interoperability between unrelated APIs by establishing a common language to pass collections back and forth.
- Reduces the effort required to learn APIs by requiring you to learn multiple ad hoc collection APIs.
- This provides static methods that perform useful functions on collections, such as sorting a list.
- This provides Wrapper implementation which adds functionality, such as synchronization, to other implementations.
And many more advantages it provides for us to use and tackle the problems of development.
Usages: Examples of different types of Interfaces are given below:
- List Interface
- Linked List
- Map Interface
- Stacks
Use Case 1: List Interface
Java
import java.util.*;
class GFG {
public static void main(String args[])
{
ArrayList<String> list = new ArrayList<String>();
list.add( "Geeks" );
list.add( "areyou" );
list.add( "working" );
list.add( "hard?" );
Iterator itr = list.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
|
Output
Geeks
areyou
working
hard?
Use Case 2: Linked List
Java
import java.util.*;
public class GFG {
public static void main(String args[])
{
LinkedList<String> al = new LinkedList<String>();
al.add( "Geeks" );
al.add( "areyou" );
al.add( "working" );
al.add( "hard?" );
Iterator<String> itr = al.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
|
Output
Geeks
areyou
working
hard?
Use Case 3: Map Interface
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
Map<Integer, String> map = new HashMap<>();
map.put( 1 , "Geeks" );
map.put( 2 , "are" );
map.put( 3 , "you" );
map.put( 4 , "working" );
Set set = map.entrySet();
Iterator itr = set.iterator();
while (itr.hasNext()) {
Map.Entry entry = (Map.Entry)itr.next();
System.out.println(entry.getKey() + " "
+ entry.getValue());
}
}
}
|
Output
1 Geeks
2 are
3 you
4 working
Use Case 4: Stacks
Java
import java.util.*;
public class GFG {
public static void main(String args[])
{
Stack<String> stack = new Stack<String>();
stack.push( "Geeks" );
stack.push( "are" );
stack.push( "you" );
stack.push( "working" );
stack.push( "hard?" );
stack.pop();
Iterator<String> itr = stack.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
|
Output
Geeks
are
you
working
Last Updated :
22 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...