Java Exercise
In this exercise, you will create a Java program that demonstrates the use of **Lists**, **Sets**, and **Maps**. First, you will create a **List** to store an ordered collection of items, a **Set** to store single, unordered items, and a **Map** to associate keys with values. Next, you will implement operations such as adding, deleting, accessing, and searching for and modifying items in these collections. This exercise will help you understand how and when to use these data structures in a Java program.
Instructions:
- Create a **List** of type
ArrayList
and add several elements to the list.
- Create a **Set** of type
HashSet
and add elements, ensuring there are no duplicates.
- Create a **Map** of type
HashMap
and associate several keys with their respective values.
- Perform delete, search, and modify operations on each of the collections.
- Print the contents of each collection to show how the elements have been manipulated.
This exercise will help you understand how **Lists**, **Sets**, and **Maps** are used in Java to efficiently store and manipulate data, and How to choose the right structure for your program's needs.
View Example Code
import java.util.ArrayList;
import java.util.HashSet;
import java.util.HashMap;
public class CollectionExercise {
public static void main(String[] args) {
// List
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
// Set
HashSet<String> set = new HashSet<>();
set.add("Red");
set.add("Green");
set.add("Blue");
// Map
HashMap<String, String> map = new HashMap<>();
map.put("First Name", "John");
map.put("Last Name", "Doe");
map.put("Age", "30");
// Display List
System.out.println("List: " + list);
// Display Set
System.out.println("Set: " + set);
// Display Map
System.out.println("Map: " + map);
}
}
Output:
List: [Apple, Banana, Cherry]
Set: [Red, Green, Blue]
Map: {First Name=John, Last Name=Doe, Age=30}
This program demonstrates how to use the **Lists**, **Sets**, and **Maps** collections in Java. Elements are added to each collection, then printed to display the contents. Lists store ordered elements, sets ensure that elements are unique, and maps associate keys with values.