Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. Java
  4. Understanding Java Collections Framework: List, Set, and Map

Understanding Java Collections Framework: List, Set, and Map

Date- Mar 16,2026 44
java collections

Overview of Java Collections Framework

The Java Collections Framework (JCF) provides a set of classes and interfaces for storing and manipulating groups of data as a single unit. It is essential for Java developers because it offers high-performance data structures and algorithms that simplify the process of managing collections of objects. The key components of the JCF include List, Set, and Map, each serving different purposes and use cases.

Prerequisites

  • Basic knowledge of Java programming language
  • Understanding of object-oriented programming concepts
  • Familiarity with Java syntax and data types
  • Java Development Kit (JDK) installed on your machine

Understanding Lists in Java

A List in Java is an ordered collection that allows duplicate elements. It provides methods to manipulate the size of the list and to access elements by their index.

Example of Using ArrayList

import java.util.ArrayList;
import java.util.List;

public class ListExample {
    public static void main(String[] args) {
        // Creating a List of String type
        List fruits = new ArrayList<>();

        // Adding elements to the List
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        // Accessing elements from the List
        System.out.println("First fruit: " + fruits.get(0)); // Output: Apple

        // Iterating over the List
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

This code demonstrates how to create a List in Java using ArrayList. The steps are as follows:

  • Import necessary classes: ArrayList and List.
  • Create a class named ListExample.
  • In the main method, instantiate a new ArrayList called fruits.
  • Add three fruit names to the list using the add method.
  • Access the first element using get(0) and print it.
  • Iterate over the list using a for-each loop to print each fruit.

Understanding Sets in Java

A Set is a collection that does not allow duplicate elements and does not maintain any specific order. The primary implementation of Set is HashSet which offers constant time performance for basic operations.

Example of Using HashSet

import java.util.HashSet;
import java.util.Set;

public class SetExample {
    public static void main(String[] args) {
        // Creating a Set of Integer type
        Set numbers = new HashSet<>();

        // Adding elements to the Set
        numbers.add(1);
        numbers.add(2);
        numbers.add(2); // duplicate, will not be added

        // Checking the size of the Set
        System.out.println("Set size: " + numbers.size()); // Output: 2

        // Iterating over the Set
        for (Integer number : numbers) {
            System.out.println(number);
        }
    }
}

This example illustrates how to work with a Set in Java. Here's a breakdown:

  • Import the HashSet and Set classes.
  • Create a class named SetExample.
  • In the main method, instantiate a new HashSet called numbers.
  • Add integers to the set, including a duplicate (2), which will be ignored.
  • Print the size of the set using size().
  • Iterate through the set and print each number.

Understanding Maps in Java

A Map is an object that maps keys to values, with each key being unique. It provides efficient retrieval of values based on their keys. The commonly used implementation of Map is HashMap.

Example of Using HashMap

import java.util.HashMap;
import java.util.Map;

public class MapExample {
    public static void main(String[] args) {
        // Creating a Map with String keys and Integer values
        Map studentGrades = new HashMap<>();

        // Adding key-value pairs to the Map
        studentGrades.put("Alice", 90);
        studentGrades.put("Bob", 85);
        studentGrades.put("Charlie", 92);

        // Accessing a value by key
        System.out.println("Alice's grade: " + studentGrades.get("Alice")); // Output: 90

        // Iterating over the Map
        for (Map.Entry entry : studentGrades.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }
}

This code demonstrates how to use a Map in Java. Here is the explanation:

  • Import the HashMap and Map classes.
  • Create a class named MapExample.
  • In the main method, instantiate a new HashMap called studentGrades.
  • Add student names as keys and grades as values using the put method.
  • Access and print Alice's grade using get.
  • Iterate through the map's entry set and print each key-value pair.

Best Practices and Common Mistakes

  • Choose the Right Collection: Understand the differences between List, Set, and Map, and select the appropriate one based on your use case.
  • Be Mindful of Duplicates: Sets do not allow duplicates, while Lists do. Ensure that your collection choice aligns with your data requirements.
  • Use Generics: Always use generics to avoid ClassCastException and to ensure type safety.
  • Resize Collections Carefully: When using dynamic collections like ArrayList, be aware of resizing overhead if the initial capacity is exceeded.

Conclusion

The Java Collections Framework is a powerful part of the Java programming language that allows developers to manage groups of objects effectively. Understanding the differences between List, Set, and Map is crucial for writing efficient and clean code. By following best practices and avoiding common mistakes, developers can leverage the capabilities of the JCF to create robust Java applications.

S
Shubham Saini
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Understanding Hibernate ORM in Java: A Comprehensive Guide
Mar 16, 2026
Mastering Java Streams API: A Comprehensive Guide
Mar 16, 2026
Understanding Generics in Java: A Comprehensive Guide
Mar 16, 2026
Understanding Polymorphism in Java: A Comprehensive Guide
Mar 16, 2026
Previous in Java
Understanding Interfaces and Abstract Classes in Java: A Comprehe…
Next in Java
Understanding Generics in Java: A Comprehensive Guide
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    HTTP Error 500.32 Failed to load ASP NET Core runtime 6,938 views
  • 2
    Error-An error occurred while processing your request in .… 11,273 views
  • 3
    Comprehensive Guide to Error Handling in Express.js 235 views
  • 4
    ConfigurationBuilder does not contain a definition for Set… 19,459 views
  • 5
    Mastering JavaScript Error Handling with Try, Catch, and F… 162 views
  • 6
    Mastering Unconditional Statements in C: A Complete Guide … 21,497 views
  • 7
    Unable to connect to any of the specified MySQL hosts 6,232 views

On this page

🎯

Interview Prep

Ace your Java interview with curated Q&As for all levels.

View Java Interview Q&As

More in Java

  • User-defined data types in java 6285 views
  • Master Java Type Casting: A Complete Guide with Examples 6253 views
  • How to add (import) java.util.List; in eclipse 5850 views
  • org.openqa.selenium.SessionNotCreatedException: session not … 5785 views
  • java.lang.IllegalStateException: The driver executable does … 5122 views
View all Java posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor