Java Sequenced Collection
The Sequenced Collection feature was introduced in Java 9.
Purpose
The purpose of Sequenced Collection is to provide a way to create collections that maintain the order of elements based on the order in which they were added.
Real-time Use Case
Imagine a scenario where you need to maintain the order of tasks in a to-do list application. You want to display the tasks in the order they were added by the user.
In this case, you can use a Sequenced Collection to store the tasks, ensuring that they are displayed in the correct order.
Executable Code
import java.util.*;
public class Main {
public static void main(String[] args) {
// Example using SequencedMap
System.out.println("Example using SequencedMap:");
Map<String, String> sequencedMap = new SequencedMap<>();
sequencedMap.put("1", "One");
sequencedMap.put("2", "Two");
sequencedMap.put("3", "Three");
System.out.println("Entries in the order they were added:");
for (Map.Entry<String, String> entry : sequencedMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Example using SequencedSet
System.out.println("\nExample using SequencedSet:");
Set<String> sequencedSet = new SequencedSet<>();
sequencedSet.add("Apple");
sequencedSet.add("Banana");
sequencedSet.add("Orange");
System.out.println("Elements in the order they were added:");
for (String element : sequencedSet) {
System.out.println(element);
}
}
}
No comments:
Post a Comment