Java List, Set, and Map Interfaces – Complete Guide with Examples
Learn the core Java Collections interfaces: List, Set, and Map, their differences, implementations, and how to use them to store, access, and manipulate data efficiently.
List, Set, and Map Interfaces in Java – Complete Detailed Tutorial
The Java Collections Framework (JCF) provides three main interfaces to handle collections: List, Set, and Map. Each has its own characteristics and usage.
1. List Interface
- Ordered collection (maintains insertion order)
- Allows duplicates
- Common implementations:
ArrayList,LinkedList,Vector,Stack - Supports index-based access
Key Methods:
| MethodDescription | |
| add(E e) | Adds element |
| get(int index) | Retrieves element at index |
| remove(int index) | Removes element at index |
| size() | Returns number of elements |
| contains(Object o) | Checks if element exists |
Example – Using List Interface
Output:
2. Set Interface
- Unordered collection (does not maintain insertion order in HashSet)
- No duplicate elements allowed
- Common implementations:
HashSet,LinkedHashSet(maintains insertion order),TreeSet(sorted)
Key Methods:
| MethodDescription | |
| add(E e) | Adds element |
| remove(Object o) | Removes element |
| contains(Object o) | Checks if element exists |
| size() | Returns number of elements |
Example – Using Set Interface
Output:
Explanation:
- Duplicates are ignored
HashSetdoes not maintain insertion order
3. Map Interface
- Stores key-value pairs
- Keys are unique, values can be duplicated
- Common implementations:
HashMap,LinkedHashMap,TreeMap
Key Methods:
| MethodDescription | |
| put(K key, V value) | Adds a key-value pair |
| get(Object key) | Retrieves value for key |
| remove(Object key) | Removes key-value pair |
| containsKey(Object key) | Checks if key exists |
| size() | Returns number of entries |
Example – Using Map Interface
Output:
Explanation:
- Keys are unique
- Values can be updated
- Maintains key-value mapping
4. Key Points
- List: ordered, allows duplicates, index-based
- Set: unordered, no duplicates, unique elements
- Map: key-value pairs, unique keys, allows duplicate values
- All interfaces provide common methods like add, remove, contains
- Can use Iterator to traverse List and Set; entrySet() for Map
5. Summary
- List, Set, and Map are the core interfaces of Collections Framework
- Chosen based on requirement: order, uniqueness, or key-value mapping
- Implementations provide optimized and ready-to-use data structures