Java Collections Framework: List, Set, Map
Java Collections Framework: List, Set, Map
๐️ 1. List Interface
A List is an ordered collection (also known as a sequence) that allows duplicate elements. Elements can be accessed by their index.
๐น Common Implementations:
ArrayList
LinkedList
Vector (rarely used now)
✅ Key Features:
Maintains insertion order
Allows duplicates
Supports random access (in ArrayList)
๐ง Example:
java
Copy
Edit
import java.util.*;
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Alice"); // Duplicate allowed
System.out.println(names); // [Alice, Bob, Alice]
๐ฆ 2. Set Interface
A Set is a collection that does not allow duplicate elements. It models the mathematical set abstraction.
๐น Common Implementations:
HashSet
LinkedHashSet
TreeSet
✅ Key Features:
No duplicates allowed
HashSet: No order
LinkedHashSet: Maintains insertion order
TreeSet: Sorted order (uses Comparable or Comparator)
๐ง Example:
java
Copy
Edit
import java.util.*;
Set<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Apple"); // Duplicate ignored
System.out.println(fruits); // [Apple, Banana] (order not guaranteed)
๐บ️ 3. Map Interface
A Map is an object that maps keys to values. It cannot contain duplicate keys; each key maps to at most one value.
๐น Common Implementations:
HashMap
LinkedHashMap
TreeMap
✅ Key Features:
Key-value pairs
No duplicate keys
HashMap: No order
LinkedHashMap: Insertion order
TreeMap: Sorted by key
๐ง Example:
java
Copy
Edit
import java.util.*;
Map<Integer, String> idMap = new HashMap<>();
idMap.put(1, "Alice");
idMap.put(2, "Bob");
idMap.put(1, "Charlie"); // Overwrites previous value for key 1
System.out.println(idMap); // {1=Charlie, 2=Bob}
๐ง Summary Table
Feature List Set Map
Allows Duplicates ✅ Yes ❌ No ✅ Values, ❌ Keys
Maintains Order ✅ (most) ✅ (LinkedHashSet) ✅ (LinkedHashMap)
Access by Index ✅ Yes ❌ No ❌ No (access by key)
Key-Value Storage ❌ No ❌ No ✅ Yes
Learn Full Stack JAVA Course in Hyderabad
Read More
Java Data Types and Variables Explained
Object-Oriented Programming in Java
Visit Our IHUB Talent Training Institute in Hyderabad
Comments
Post a Comment