Logo
Unit 12 – Collections Framework in Java

Collections Framework in Java

Duration: 5 minutes

Hello, Java learners!

In this session, we will explore the Collections Framework in Java, a powerful toolkit that provides an architecture to store and manipulate groups of objects. Java collections can do everything you might imagine: searching, sorting, insertion, manipulation, and deletion.We’ll focus on three commonly used collections: ArrayList, HashSet, and HashMap.

1. ArrayList

ArrayList is a resizable array implementation of the List interface. It’s similar to an array, but with more flexibility. Example of using ArrayList:

import java.util.ArrayList;
public class Main {
 public static void main(String[] args) {
 ArrayList fruits = new ArrayList<>();
 fruits.add("Apple");
 fruits.add("Banana");
 fruits.add("Cherry");
 System.out.println(fruits); // Output: [Apple, Banana, Cherry]
 }
}

2. HashSet

HashSet implements the Set interface, backed by a hash table. It doesn’t maintain any order and ensures that there are no duplicate elements.Example of using HashSet:

import java.util.HashSet;
public class Main {
 public static void main(String[] args) {
 HashSet cities = new HashSet<>();
 cities.add("New York");
 cities.add("London");
 cities.add("New York");
 System.out.println(cities); // Output: [New York, London]
 }
}

3. HashMap

HashMap implements the Map interface and is used for storing key-value pairs. It provides constant-time performance for basic operations (get and put).Example of using HashMap:

import java.util.HashMap;
public class Main {
 public static void main(String[] args) {
 HashMap ageMap = new HashMap<>();
 ageMap.put("Alice", 25);
 ageMap.put("Bob", 30);
 System.out.println(ageMap); // Output: {Alice=25, Bob=30}
 }
}

Exercise: Using Collections to Solve a Problem

Now, let’s practice using these collections. Your task is to:- Create an ArrayList to store a list of book titles.

  • Use a HashSet to store a unique collection of student names.
  • Create a HashMap to map employee names to their respective departments.

Conclusion

Congratulations! You’ve just taken a step further into Java’s Collections Framework. These collections are incredibly useful for handling data in Java applications, providing both flexibility and powerful functionality.Experiment with these different collections and try implementing them in various scenarios. This will help you understand when and how to use each type of collection effectively.Happy coding, and keep exploring the vast capabilities of Java collections!

Next Tutorial: Java Packages

5 minutes Minutes

Continue

Code on the Go with our Mobile App!

Unleash your coding potential anytime, anywhere!

Download Now!