Java 21 Sequenced Collections

beginner
15 min

Java 21 Sequenced Collections

Welcome to our comprehensive guide on Java Sequenced Collections! In this tutorial, we'll dive deep into Lists, Sets, and Maps – essential data structures that every Java developer should know. Let's get started! šŸŽÆ

Lists šŸ“

Lists are ordered collections of objects. They can contain duplicate elements and maintain the order of insertion. Here's an example of a simple ArrayList:

java
import java.util.ArrayList; ArrayList<String> fruits = new ArrayList<String>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Mango"); // Access elements System.out.println(fruits.get(0)); // Output: Apple // Check size System.out.println(fruits.size()); // Output: 3

šŸ’” Pro Tip: To add an element at a specific index, use fruits.add(1, "Orange").

Quiz

Quick Quiz
Question 1 of 1

Which of the following methods can be used to check the size of an ArrayList?

Sets šŸŽÆ

Sets are unordered collections of unique elements. They are useful when you need to store distinct values. Here's an example of a HashSet:

java
import java.util.HashSet; HashSet<String> fruitsSet = new HashSet<String>(); fruitsSet.add("Apple"); fruitsSet.add("Banana"); fruitsSet.add("Mango"); fruitsSet.add("Apple"); // This won't be added since sets contain unique elements // Access elements System.out.println(fruitsSet); // Output: [Apple, Banana, Mango]

šŸ’” Pro Tip: To check if a set contains a specific element, use fruitsSet.contains("Apple").

Quiz

Quick Quiz
Question 1 of 1

Which of the following methods can be used to check if a HashSet contains a specific element?

Maps šŸ“

Maps are collections of key-value pairs. They are useful when you need to associate values with unique keys. Here's an example of a HashMap:

java
import java.util.HashMap; HashMap<String, Integer> fruitWeights = new HashMap<String, Integer>(); fruitWeights.put("Apple", 150); fruitWeights.put("Banana", 105); fruitWeights.put("Mango", 230); // Access values System.out.println(fruitWeights.get("Apple")); // Output: 150

šŸ’” Pro Tip: To check if a Map contains a specific key, use fruitWeights.containsKey("Apple").

Quiz

Quick Quiz
Question 1 of 1

Which of the following methods can be used to check if a HashMap contains a specific key?

That's it for our Java Sequenced Collections tutorial! These data structures are fundamental in Java programming, and mastering them will help you create more efficient and powerful code. Happy coding! šŸ’”