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

Get Directions

Comments

Popular posts from this blog

Handling Frames and Iframes Using Playwright

Cybersecurity Internship Opportunities in Hyderabad for Freshers

Tosca for API Testing: A Step-by-Step Tutorial