In Java, you have several data structures available for storing and manipulating collections of elements, including lists, sets, and maps. Here are examples of how you can use these data structures:
- Lists: A list is an ordered collection that allows duplicate elements. The most commonly used implementation of the List interface in Java is
ArrayList
. Here’s an example:
import java.util.ArrayList; import java.util.List; public class ListExample { public static void main(String[] args) { List<String> fruits = new ArrayList<>(); // Adding elements to the list fruits.add("Apple"); fruits.add("Banana"); fruits.add("Orange"); // Accessing elements by index String firstFruit = fruits.get(0); System.out.println("First fruit: " + firstFruit); // Iterating over the list for (String fruit : fruits) { System.out.println(fruit); } } }
Output:
First fruit: Apple Apple Banana Orange
- Sets: A set is a collection that does not allow duplicate elements. The
HashSet
implementation is commonly used. Here’s an example:
import java.util.HashSet; import java.util.Set; public class SetExample { public static void main(String[] args) { Set<String> uniqueNames = new HashSet<>(); // Adding elements to the set uniqueNames.add("Alice"); uniqueNames.add("Bob"); uniqueNames.add("Alice"); // Duplicate element, won't be added // Checking if an element exists in the set boolean containsBob = uniqueNames.contains("Bob"); System.out.println("Set contains Bob: " + containsBob); // Iterating over the set for (String name : uniqueNames) { System.out.println(name); } } }
Output:
Set contains Bob: true Alice Bob
- Maps: A map is a collection of key-value pairs, where each key is unique. The
HashMap
implementation is commonly used. Here’s an example:
import java.util.HashMap; import java.util.Map; public class MapExample { public static void main(String[] args) { Map<String, Integer> wordCount = new HashMap<>(); // Adding elements to the map wordCount.put("apple", 3); wordCount.put("banana", 2); wordCount.put("orange", 5); // Accessing values by key int count = wordCount.get("banana"); System.out.println("Count of banana: " + count); // Iterating over the map for (Map.Entry<String, Integer> entry : wordCount.entrySet()) { String word = entry.getKey(); int value = entry.getValue(); System.out.println(word + ": " + value); } } }
Output:
Count of banana: 2 apple: 3 banana: 2 orange: 5
These examples demonstrate the basic usage of lists, sets, and maps in Java. There are additional methods and features available for each data structure, so make sure to consult the Java documentation for more information.