Collections in Java

In Java, a collection is a group of objects, which can be of the same or different types, that are treated as a single entity. Collections are used to store, manipulate and retrieve data efficiently. Java provides a number of built-in collection classes and interfaces in the java.util package.

Some of the commonly used collection interfaces in Java are:

  1. List – An ordered collection of elements that allows duplicates. The elements can be accessed by their index position.
  2. Set – A collection that does not allow duplicates. The elements are not ordered.
  3. Map – A collection that maps unique keys to values. A key is an object that is used to retrieve a value.

Some of the commonly used collection classes in Java are:

  1. ArrayList – A resizable array that implements the List interface. It can grow or shrink dynamically as elements are added or removed.
  2. LinkedList – A linked list that implements the List interface. It provides constant-time insertion and deletion of elements from any position in the list.
  3. HashSet – A set that uses a hash table to store elements. It provides constant-time performance for the basic operations like add, remove, contains, and size.
  4. HashMap – A map that uses a hash table to store key-value pairs. It provides constant-time performance for the basic operations like get, put, containsKey, and size.

Java also provides some other collection classes and interfaces like PriorityQueue, TreeSet, TreeMap, etc. that can be used for specific use cases.

To use collections in Java, you need to import the java.util package and create an instance of the desired collection class. For example, to create an ArrayList, you can do:

import java.util.ArrayList;

ArrayList<String> list = new ArrayList<String>();

This creates an ArrayList of Strings. You can then add elements to the list using the add method and retrieve elements using the get method.

What is Collection in Java:

In Java, a Collection is a framework that provides an architecture to store, manipulate and retrieve a group of objects. It is a concept that represents a group of objects, where each object is considered as an element in the collection.

Java Collections framework provides a set of interfaces, classes, and algorithms that help in implementing collections. The collection framework is designed to meet several objectives, such as:

  1. To provide a common interface to store, manipulate and retrieve collections of objects.
  2. To provide a uniform way to access the elements in the collection irrespective of the type of collection.
  3. To provide a set of high-performance implementations of commonly used collections like List, Set, Map, etc.
  4. To provide a set of algorithms to perform operations like searching, sorting, and filtering on the collections.

Some of the commonly used collection interfaces in Java are:

  1. List – An ordered collection of elements that allows duplicates. The elements can be accessed by their index position.
  2. Set – A collection that does not allow duplicates. The elements are not ordered.
  3. Map – A collection that maps unique keys to values. A key is an object that is used to retrieve a value.

Java provides a wide range of collection classes that implement these interfaces. For example, ArrayList and LinkedList implement the List interface, HashSet and TreeSet implement the Set interface, and HashMap and TreeMap implement the Map interface.

The Java Collections framework is an important part of the Java Standard Library and is widely used in Java applications for storing, manipulating and retrieving data efficiently.

What is a framework in Java:

In Java, a framework is a pre-written and reusable code that provides a set of tools, guidelines, and best practices to help developers create software applications efficiently. It is a set of classes, interfaces, and libraries that provide a foundation for building applications.

A framework is designed to solve a particular problem or to address a specific set of requirements. It provides a standard structure for developing software applications, which helps in reducing the development time and effort. A framework also provides a common set of tools and libraries that can be used by different developers, which helps in maintaining consistency and standardization in the development process.

Some of the popular Java frameworks are:

  1. Spring Framework – A widely used framework for building enterprise applications. It provides a comprehensive programming and configuration model for modern Java-based enterprise applications.
  2. Hibernate – A framework for object-relational mapping (ORM) that provides a simple way to map Java classes to database tables.
  3. Struts – A framework for building web applications based on the Model-View-Controller (MVC) architecture.
  4. JavaServer Faces (JSF) – A framework for building user interfaces for web applications.

Frameworks help in reducing the time and effort required for developing software applications by providing a pre-built structure, libraries, and tools. This enables developers to focus on the business logic of the application rather than on the low-level details of the implementation. By using a framework, developers can improve the quality and maintainability of their code, as well as reduce the risk of errors and bugs.

Hierarchy of Collection Framework:

The Collection Framework in Java provides a hierarchy of interfaces and classes that are used to store, manipulate and retrieve a group of objects. The hierarchy can be broadly classified into two main categories:

  1. Collection Interfaces – These are a set of interfaces that define the core functionality of the Collection Framework. The Collection Interfaces are:
  • Collection – The root interface of the collection hierarchy. It defines the basic operations that all collections should support such as adding, removing, and accessing elements.
  • List – An ordered collection of elements that allows duplicates. The elements can be accessed by their index position.
  • Set – A collection that does not allow duplicates. The elements are not ordered.
  • Queue – A collection used to store elements prior to processing.
  • Deque – A double-ended queue that supports insertion and removal of elements at both ends.
  1. Collection Classes – These are a set of classes that implement the Collection Interfaces. The Collection Classes are:
  • AbstractCollection – An abstract implementation of the Collection interface that provides common methods that can be used by all Collection classes.
  • ArrayList – A resizable array that implements the List interface. It can grow or shrink dynamically as elements are added or removed.
  • LinkedList – A linked list that implements the List interface. It provides constant-time insertion and deletion of elements from any position in the list.
  • HashSet – A set that uses a hash table to store elements. It provides constant-time performance for the basic operations like add, remove, contains, and size.
  • LinkedHashSet – A set that maintains the insertion order of elements.
  • TreeSet – A set that is sorted according to the natural ordering of its elements, or by a specified Comparator.
  • HashMap – A map that uses a hash table to store key-value pairs. It provides constant-time performance for the basic operations like get, put, containsKey, and size.
  • LinkedHashMap – A map that maintains the insertion order of its elements.
  • TreeMap – A map that is sorted according to the natural ordering of its keys, or by a specified Comparator.

By using the Collection Framework in Java, developers can easily manipulate and store data in different data structures, depending on the use case. The hierarchy of interfaces and classes provides a consistent and standardized way to work with collections, regardless of the specific implementation being used.

Methods of Collection interface:

The java.util.Collection interface in Java is the root interface of the collection hierarchy, and it defines a set of common methods that are implemented by all the collection classes. Some of the most commonly used methods of the Collection interface are:

  1. boolean add(E e): Adds the specified element to the collection. Returns true if the collection was modified, false otherwise.
  2. boolean addAll(Collection<? extends E> c): Adds all the elements in the specified collection to this collection. Returns true if the collection was modified, false otherwise.
  3. void clear(): Removes all the elements from the collection.
  4. boolean contains(Object o): Returns true if the collection contains the specified element, false otherwise.
  5. boolean containsAll(Collection<?> c): Returns true if the collection contains all the elements in the specified collection, false otherwise.
  6. boolean equals(Object o): Returns true if the specified object is equal to this collection, false otherwise.
  7. int hashCode(): Returns the hash code value for this collection.
  8. boolean isEmpty(): Returns true if the collection contains no elements, false otherwise.
  9. Iterator<E> iterator(): Returns an iterator over the elements in the collection.
  10. boolean remove(Object o): Removes the specified element from the collection. Returns true if the collection was modified, false otherwise.
  11. boolean removeAll(Collection<?> c): Removes all the elements in the specified collection from this collection. Returns true if the collection was modified, false otherwise.
  12. boolean retainAll(Collection<?> c): Retains only the elements in this collection that are contained in the specified collection. Returns true if the collection was modified, false otherwise.
  13. int size(): Returns the number of elements in the collection.
  14. Object[] toArray(): Returns an array containing all the elements in the collection.
  15. <T> T[] toArray(T[] a): Returns an array containing all the elements in the collection, using the specified array if it is large enough. If the specified array is not large enough, a new array is allocated with the same runtime type as the specified array.

These methods provide a basic set of operations to manipulate the elements in a collection, such as adding, removing, iterating, and checking the contents of the collection. Different collection classes may provide additional methods to support their specific functionality.

Iterator interface:

The java.util.Iterator interface in Java is a part of the Collection Framework, and it provides a way to iterate over the elements of a collection. An iterator can be used to traverse the elements of a collection sequentially, without having to know the implementation details of the collection.

The Iterator interface defines the following methods:

  1. boolean hasNext(): Returns true if the iteration has more elements.
  2. E next(): Returns the next element in the iteration.
  3. void remove(): Removes the last element returned by the iterator (optional operation).

The hasNext() method returns true if there are more elements in the collection to iterate over. The next() method returns the next element in the iteration, and throws a NoSuchElementException if there are no more elements in the collection. The remove() method removes the last element returned by the iterator from the underlying collection, and is an optional operation that may not be supported by all collection implementations.

Here’s an example of how to use an Iterator to iterate over a List:

List<String> myList = new ArrayList<>();
myList.add("foo");
myList.add("bar");
myList.add("baz");

Iterator<String> iterator = myList.iterator();
while (iterator.hasNext()) {
    String element = iterator.next();
    System.out.println(element);
}

This code creates a List of strings, and then creates an Iterator to iterate over the elements of the list. The hasNext() method is used to check if there are more elements in the list, and the next() method is used to retrieve the next element in the iteration. The loop continues until there are no more elements in the list.

List Interface:

The java.util.List interface in Java is a sub-interface of the java.util.Collection interface and represents an ordered collection of elements, where duplicate elements are allowed. List elements can be accessed by their index in the list, and the list maintains insertion order of elements.

The List interface defines the following methods:

  1. void add(int index, E element): Inserts the specified element at the specified position in the list.
  2. boolean addAll(int index, Collection<? extends E> c): Inserts all elements in the specified collection into the list at the specified position.
  3. E get(int index): Returns the element at the specified position in the list.
  4. int indexOf(Object o): Returns the index of the first occurrence of the specified element in the list, or -1 if the list does not contain the element.
  5. int lastIndexOf(Object o): Returns the index of the last occurrence of the specified element in the list, or -1 if the list does not contain the element.
  6. ListIterator<E> listIterator(): Returns a list iterator over the elements in the list (in proper sequence).
  7. ListIterator<E> listIterator(int index): Returns a list iterator over the elements in the list (in proper sequence), starting at the specified position in the list.
  8. E remove(int index): Removes the element at the specified position in the list, and returns the removed element.
  9. E set(int index, E element): Replaces the element at the specified position in the list with the specified element.
  10. List<E> subList(int fromIndex, int toIndex): Returns a view of the portion of the list between the specified fromIndex, inclusive, and toIndex, exclusive.

The List interface also inherits all the methods of the Collection interface, including size(), isEmpty(), contains(Object o), iterator(), toArray(), remove(Object o), containsAll(Collection<?> c), addAll(Collection<? extends E> c), removeAll(Collection<?> c), retainAll(Collection<?> c), and clear().

Here’s an example of how to use some of the methods of a List:

List<String> myList = new ArrayList<>();
myList.add("foo");
myList.add("bar");
myList.add("baz");

String element = myList.get(1); // returns "bar"
int index = myList.indexOf("baz"); // returns 2
myList.add(1, "qux"); // inserts "qux" at index 1

System.out.println(myList); // prints [foo, qux, bar, baz]

This code creates a List of strings, and adds some elements to it using the add() method. It then retrieves an element from the list using the get() method, gets the index of an element in the list using the indexOf() method, and inserts an element at a specific position in the list using the add(int index, E element) method. Finally, it prints the contents of the list using the toString() method.

Collection Interface:

The java.util.Collection interface in Java is the root interface in the Collection Framework hierarchy. It represents a group of objects known as elements, and provides operations for working with collections of objects. A collection may contain duplicate elements, and the elements are not ordered.

The Collection interface defines the following methods:

  1. int size(): Returns the number of elements in the collection.
  2. boolean isEmpty(): Returns true if the collection contains no elements.
  3. boolean contains(Object o): Returns true if the collection contains the specified element.
  4. Iterator<E> iterator(): Returns an iterator over the elements in the collection.
  5. Object[] toArray(): Returns an array containing all of the elements in the collection.
  6. <T> T[] toArray(T[] a): Returns an array containing all of the elements in the collection, using the specified array if it is large enough; otherwise, a new array of the same runtime type is allocated for this purpose.
  7. boolean add(E e): Adds the specified element to the collection.
  8. boolean remove(Object o): Removes the specified element from the collection.
  9. boolean containsAll(Collection<?> c): Returns true if the collection contains all of the elements in the specified collection.
  10. boolean addAll(Collection<? extends E> c): Adds all of the elements in the specified collection to the collection.
  11. boolean removeAll(Collection<?> c): Removes all of the elements in the specified collection from the collection.
  12. boolean retainAll(Collection<?> c): Removes all elements from the collection except those in the specified collection.
  13. void clear(): Removes all elements from the collection.

The Collection interface is extended by several sub-interfaces, including List, Set, and Queue. These sub-interfaces define additional methods for working with specific types of collections.

Here’s an example of how to use some of the methods of a Collection:

Collection<String> myCollection = new ArrayList<>();
myCollection.add("foo");
myCollection.add("bar");
myCollection.add("baz");

boolean containsFoo = myCollection.contains("foo"); // returns true
boolean containsQux = myCollection.contains("qux"); // returns false

myCollection.remove("bar");
boolean containsBar = myCollection.contains("bar"); // returns false

Object[] array = myCollection.toArray(); // returns {"foo", "baz"}

myCollection.clear();
boolean isEmpty = myCollection.isEmpty(); // returns true

This code creates a Collection of strings, adds some elements to it using the add() method, and checks if the collection contains certain elements using the contains() method. It also removes an element from the collection using the remove() method, and retrieves an array containing all the elements in the collection using the toArray() method. Finally, it clears the collection using the clear() method, and checks if the collection is empty using the isEmpty() method.

ArrayList:

ArrayList is a class in the Java Collections Framework that implements the List interface. It is an ordered collection of elements that can grow or shrink dynamically as elements are added to or removed from it.

An ArrayList is similar to an array in that it stores elements in a contiguous block of memory, but it differs in that it can dynamically resize itself to accommodate more elements. It also provides a number of methods for manipulating its elements, such as adding or removing elements at specific positions, searching for elements, and sorting the elements.

Some of the most commonly used methods of the ArrayList class are:

  1. add(E element): Adds the specified element to the end of the list.
  2. add(int index, E element): Inserts the specified element at the specified position in the list.
  3. remove(int index): Removes the element at the specified position in the list.
  4. remove(Object obj): Removes the first occurrence of the specified element from the list.
  5. get(int index): Returns the element at the specified position in the list.
  6. set(int index, E element): Replaces the element at the specified position in the list with the specified element.
  7. size(): Returns the number of elements in the list.
  8. clear(): Removes all elements from the list.
  9. contains(Object obj): Returns true if the list contains the specified element.
  10. indexOf(Object obj): Returns the index of the first occurrence of the specified element in the list.
  11. lastIndexOf(Object obj): Returns the index of the last occurrence of the specified element in the list.
  12. isEmpty(): Returns true if the list contains no elements.

Here’s an example of how to use an ArrayList:

ArrayList<String> list = new ArrayList<String>();

list.add("apple");
list.add("banana");
list.add("orange");
list.add("pear");

System.out.println(list.get(1)); // prints "banana"

list.remove(2);

System.out.println(list); // prints "[apple, banana, pear]"

System.out.println(list.contains("banana")); // prints "true"

In this example, we create a new ArrayList and add four elements to it. We then print the second element in the list using the get() method, remove the third element using the remove() method, and print the remaining elements in the list using the toString() method. Finally, we check if the list contains the string “banana” using the contains() method.

LinkedList:

LinkedList is a class in the Java Collections Framework that implements the List and Deque interfaces. It is a doubly linked list that stores elements in a non-contiguous block of memory. Each element in the list has a reference to the next and previous elements, allowing for efficient insertion and removal of elements at any position in the list.

Some of the most commonly used methods of the LinkedList class are:

  1. add(E element): Adds the specified element to the end of the list.
  2. add(int index, E element): Inserts the specified element at the specified position in the list.
  3. remove(int index): Removes the element at the specified position in the list.
  4. remove(Object obj): Removes the first occurrence of the specified element from the list.
  5. get(int index): Returns the element at the specified position in the list.
  6. set(int index, E element): Replaces the element at the specified position in the list with the specified element.
  7. size(): Returns the number of elements in the list.
  8. clear(): Removes all elements from the list.
  9. contains(Object obj): Returns true if the list contains the specified element.
  10. indexOf(Object obj): Returns the index of the first occurrence of the specified element in the list.
  11. lastIndexOf(Object obj): Returns the index of the last occurrence of the specified element in the list.
  12. addFirst(E element): Inserts the specified element at the beginning of the list.
  13. addLast(E element): Inserts the specified element at the end of the list.
  14. removeFirst(): Removes and returns the first element in the list.
  15. removeLast(): Removes and returns the last element in the list.
  16. getFirst(): Returns the first element in the list.
  17. getLast(): Returns the last element in the list.
  18. isEmpty(): Returns true if the list contains no elements.

Here’s an example of how to use a LinkedList:

LinkedList<String> list = new LinkedList<String>();

list.add("apple");
list.add("banana");
list.add("orange");
list.add("pear");

System.out.println(list.get(1)); // prints "banana"

list.remove(2);

System.out.println(list); // prints "[apple, banana, pear]"

System.out.println(list.contains("banana")); // prints "true"

In this example, we create a new LinkedList and add four elements to it. We then print the second element in the list using the get() method, remove the third element using the remove() method, and print the remaining elements in the list using the toString() method. Finally, we check if the list contains the string “banana” using the contains() method.

Vector:

Vector is a class in the Java Collections Framework that implements the List interface and is similar to an ArrayList. However, unlike ArrayList, Vector is thread-safe, meaning that it can be safely accessed and modified by multiple threads simultaneously without causing any unexpected behavior.

Some of the most commonly used methods of the Vector class are:

  1. add(E element): Adds the specified element to the end of the vector.
  2. add(int index, E element): Inserts the specified element at the specified position in the vector.
  3. remove(int index): Removes the element at the specified position in the vector.
  4. remove(Object obj): Removes the first occurrence of the specified element from the vector.
  5. get(int index): Returns the element at the specified position in the vector.
  6. set(int index, E element): Replaces the element at the specified position in the vector with the specified element.
  7. size(): Returns the number of elements in the vector.
  8. clear(): Removes all elements from the vector.
  9. contains(Object obj): Returns true if the vector contains the specified element.
  10. indexOf(Object obj): Returns the index of the first occurrence of the specified element in the vector.
  11. lastIndexOf(Object obj): Returns the index of the last occurrence of the specified element in the vector.
  12. addElement(E element): Adds the specified element to the end of the vector.
  13. removeElement(Object obj): Removes the first occurrence of the specified element from the vector.
  14. elementAt(int index): Returns the element at the specified position in the vector.
  15. setElementAt(E element, int index): Replaces the element at the specified position in the vector with the specified element.

Here’s an example of how to use a Vector:

Vector<String> vector = new Vector<String>();

vector.add("apple");
vector.add("banana");
vector.add("orange");
vector.add("pear");

System.out.println(vector.get(1)); // prints "banana"

vector.remove(2);

System.out.println(vector); // prints "[apple, banana, pear]"

System.out.println(vector.contains("banana")); // prints "true"

In this example, we create a new Vector and add four elements to it. We then print the second element in the vector using the get() method, remove the third element using the remove() method, and print the remaining elements in the vector using the toString() method. Finally, we check if the vector contains the string “banana” using the contains() method.

Stack:

In Java, Stack is a class that extends the Vector class and implements the List interface, providing a last-in-first-out (LIFO) data structure. This means that the last element added to the stack is the first element to be removed. The methods of Stack are synchronized, making it thread-safe.

Some of the most commonly used methods of the Stack class are:

  1. push(E item): Pushes an item onto the top of this stack.
  2. pop(): Removes the object at the top of this stack and returns that object.
  3. peek(): Looks at the object at the top of this stack without removing it from the stack.
  4. empty(): Tests if this stack is empty.
  5. search(Object o): Returns the 1-based position where an object is on this stack.

Here is an example of how to use a Stack:

Stack<String> stack = new Stack<String>();

stack.push("apple");
stack.push("banana");
stack.push("orange");
stack.push("pear");

System.out.println(stack.peek()); // prints "pear"

stack.pop();

System.out.println(stack); // prints "[apple, banana, orange]"

System.out.println(stack.search("banana")); // prints "2"

In this example, we create a new Stack and add four elements to it using the push() method. We then print the top element of the stack using the peek() method, remove the top element from the stack using the pop() method, and print the remaining elements in the stack using the toString() method. Finally, we use the search() method to find the position of the string “banana” in the stack.

Queue Interface:

In Java, the Queue interface represents a collection of elements that can be processed in a specific order. It is an extension of the Collection interface and specifies a set of methods for adding, removing, and inspecting elements in the queue.

The Queue interface is designed to support the typical operations of a queue data structure, such as adding elements to the back of the queue and removing elements from the front of the queue. The Queue interface provides several methods for these operations, such as:

  1. add(E e): Adds the specified element to the end of the queue.
  2. offer(E e): Inserts the specified element into the queue.
  3. remove(): Removes and returns the element at the front of the queue.
  4. poll(): Retrieves and removes the head of the queue, or returns null if the queue is empty.
  5. element(): Retrieves, but does not remove, the head of the queue.
  6. peek(): Retrieves, but does not remove, the head of the queue, or returns null if the queue is empty.

The Queue interface is extended by several subinterfaces, including Deque, which stands for “double-ended queue” and provides methods for adding and removing elements from both the front and back of the queue.

Here is an example of how to use a Queue:

Queue<String> queue = new LinkedList<String>();

queue.offer("apple");
queue.offer("banana");
queue.offer("orange");
queue.offer("pear");

System.out.println(queue.peek()); // prints "apple"

queue.poll();

System.out.println(queue); // prints "[banana, orange, pear]"

In this example, we create a new Queue using a LinkedList implementation and add four elements to it using the offer() method. We then print the head of the queue using the peek() method, remove the head of the queue using the poll() method, and print the remaining elements in the queue using the toString() method.

PriorityQueue:

In Java, the PriorityQueue class is an implementation of the Queue interface that provides a priority queue data structure. Elements in a PriorityQueue are ordered according to their natural ordering or a custom comparator provided at the time of construction.

The PriorityQueue class is similar to a regular Queue, but with the added functionality of ordering elements based on their priority. The PriorityQueue class provides several methods for adding, removing, and inspecting elements in the queue, such as:

  1. add(E e): Inserts the specified element into the queue.
  2. offer(E e): Inserts the specified element into the queue.
  3. remove(): Retrieves and removes the head of the queue.
  4. poll(): Retrieves and removes the head of the queue, or returns null if the queue is empty.
  5. peek(): Retrieves, but does not remove, the head of the queue.
  6. element(): Retrieves, but does not remove, the head of the queue.

Here is an example of how to use a PriorityQueue:

PriorityQueue<Integer> queue = new PriorityQueue<Integer>();

queue.add(3);
queue.add(1);
queue.add(4);
queue.add(2);

System.out.println(queue.peek()); // prints "1"

queue.poll();

System.out.println(queue); // prints "[2, 3, 4]"

In this example, we create a new PriorityQueue and add four elements to it using the add() method. The elements are ordered based on their natural ordering (in this case, numerical order). We then print the head of the queue using the peek() method, remove the head of the queue using the poll() method, and print the remaining elements in the queue using the toString() method.

Deque Interface:

In Java, the Deque interface (short for “double-ended queue”) is a subtype of the Queue interface that allows elements to be inserted and removed from both ends of the queue. It provides a more complete and consistent set of LIFO (last-in-first-out) and FIFO (first-in-first-out) operations than those provided by the Stack and Queue interfaces.

The Deque interface defines several methods for adding, removing, and examining elements at both ends of the queue, such as:

  1. addFirst(E e): Inserts the specified element at the front of the queue.
  2. addLast(E e): Inserts the specified element at the end of the queue.
  3. offerFirst(E e): Inserts the specified element at the front of the queue.
  4. offerLast(E e): Inserts the specified element at the end of the queue.
  5. removeFirst(): Removes and returns the first element of the queue.
  6. removeLast(): Removes and returns the last element of the queue.
  7. pollFirst(): Retrieves and removes the first element of the queue, or returns null if the queue is empty.
  8. pollLast(): Retrieves and removes the last element of the queue, or returns null if the queue is empty.
  9. getFirst(): Retrieves, but does not remove, the first element of the queue.
  10. getLast(): Retrieves, but does not remove, the last element of the queue.
  11. peekFirst(): Retrieves, but does not remove, the first element of the queue, or returns null if the queue is empty.
  12. peekLast(): Retrieves, but does not remove, the last element of the queue, or returns null if the queue is empty.

The Deque interface is implemented by several classes in the Java Collections Framework, such as ArrayDeque, LinkedList, and LinkedBlockingDeque.

Here is an example of how to use a Deque:

Deque<String> deque = new LinkedList<String>();

deque.addFirst("apple");
deque.addLast("banana");
deque.addLast("orange");
deque.addFirst("pear");

System.out.println(deque.peekFirst()); // prints "pear"

deque.pollLast();

System.out.println(deque); // prints "[pear, apple, banana]"

In this example, we create a new Deque using a LinkedList implementation and add four elements to it using the addFirst() and addLast() methods. We then print the first element of the deque using the peekFirst() method, remove the last element of the deque using the pollLast() method, and print the remaining elements in the deque using the toString() method.

ArrayDeque:

In Java, the ArrayDeque class is a resizable array implementation of the Deque interface that provides constant time performance for adding or removing elements from both ends of the deque. It is not thread-safe, and does not allow null elements.

The ArrayDeque class provides several methods for adding, removing, and inspecting elements at both ends of the deque, such as:

  1. addFirst(E e): Inserts the specified element at the front of the deque.
  2. addLast(E e): Inserts the specified element at the end of the deque.
  3. offerFirst(E e): Inserts the specified element at the front of the deque.
  4. offerLast(E e): Inserts the specified element at the end of the deque.
  5. removeFirst(): Removes and returns the first element of the deque.
  6. removeLast(): Removes and returns the last element of the deque.
  7. pollFirst(): Retrieves and removes the first element of the deque, or returns null if the deque is empty.
  8. pollLast(): Retrieves and removes the last element of the deque, or returns null if the deque is empty.
  9. getFirst(): Retrieves, but does not remove, the first element of the deque.
  10. getLast(): Retrieves, but does not remove, the last element of the deque.
  11. peekFirst(): Retrieves, but does not remove, the first element of the deque, or returns null if the deque is empty.
  12. peekLast(): Retrieves, but does not remove, the last element of the deque, or returns null if the deque is empty.

Here is an example of how to use an ArrayDeque:

ArrayDeque<Integer> deque = new ArrayDeque<Integer>();

deque.addFirst(1);
deque.addLast(2);
deque.addLast(3);
deque.addFirst(0);

System.out.println(deque.peekFirst()); // prints "0"

deque.pollLast();

System.out.println(deque); // prints "[0, 1, 2]"

In this example, we create a new ArrayDeque and add four elements to it using the addFirst() and addLast() methods. We then print the first element of the deque using the peekFirst() method, remove the last element of the deque using the pollLast() method, and print the remaining elements in the deque using the toString() method.

Set Interface:

In Java, the Set interface is part of the Collection framework and is used to store a collection of unique elements. It extends the Collection interface and does not allow duplicate elements. The Set interface is implemented by several classes in Java, including HashSet, TreeSet, and LinkedHashSet.

Some of the important characteristics of the Set interface are:

  1. It does not maintain any order of elements.
  2. It cannot contain duplicate elements.
  3. It allows at most one null element.

The Set interface provides several methods for adding, removing, and checking for the presence of elements in the set, such as:

  1. add(E e): Adds the specified element to the set if it is not already present.
  2. remove(Object o): Removes the specified element from the set if it is present.
  3. contains(Object o): Returns true if the set contains the specified element.
  4. isEmpty(): Returns true if the set is empty.
  5. size(): Returns the number of elements in the set.
  6. clear(): Removes all elements from the set.
  7. iterator(): Returns an iterator over the elements in the set.

Here’s an example of how to use a HashSet:

Set<String> set = new HashSet<String>();

set.add("apple");
set.add("banana");
set.add("orange");
set.add("apple"); // This will not be added to the set

System.out.println(set.size()); // prints "3"

set.remove("banana");

System.out.println(set.contains("banana")); // prints "false"

In this example, we create a new HashSet and add four elements to it using the add() method. Since “apple” is already in the set, it is not added again. We then print the size of the set using the size() method, remove “banana” from the set using the remove() method, and check if the set contains “banana” using the contains() method.

HashSet:

In Java, HashSet is a class that implements the Set interface and is used to store a collection of unique elements. It is based on a hash table data structure and provides constant-time performance for adding, removing, and checking for the presence of elements in the set. HashSet does not maintain any order of elements and can contain at most one null element.

Some of the important characteristics of HashSet are:

  1. It uses the hashCode() and equals() methods to determine whether two objects are equal.
  2. It does not allow duplicate elements.
  3. It allows at most one null element.

The HashSet class provides several methods for adding, removing, and checking for the presence of elements in the set, such as:

  1. add(E e): Adds the specified element to the set if it is not already present.
  2. remove(Object o): Removes the specified element from the set if it is present.
  3. contains(Object o): Returns true if the set contains the specified element.
  4. isEmpty(): Returns true if the set is empty.
  5. size(): Returns the number of elements in the set.
  6. clear(): Removes all elements from the set.
  7. iterator(): Returns an iterator over the elements in the set.

Here’s an example of how to use a HashSet:

Set<String> set = new HashSet<String>();

set.add("apple");
set.add("banana");
set.add("orange");
set.add("apple"); // This will not be added to the set

System.out.println(set.size()); // prints "3"

set.remove("banana");

System.out.println(set.contains("banana")); // prints "false"

 

In this example, we create a new HashSet and add four elements to it using the add() method. Since “apple” is already in the set, it is not added again. We then print the size of the set using the size() method, remove “banana” from the set using the remove() method, and check if the set contains “banana” using the contains() method.

LinkedHashSet:

In Java, LinkedHashSet is a class that implements the Set interface and is similar to a HashSet, but maintains the insertion order of elements. LinkedHashSet is implemented using a combination of a hash table and a linked list, which provides the functionality of a HashSet along with maintaining the order of elements.

LinkedHashSet has the following characteristics:

  1. It maintains the order of elements in which they were inserted into the set.
  2. It does not allow duplicate elements.
  3. It allows at most one null element.

The LinkedHashSet class provides the same methods as the HashSet class for adding, removing, and checking for the presence of elements in the set. The only difference is that LinkedHashSet also provides two additional methods:

  1. iterator(): Returns an iterator over the elements in the set in the order in which they were inserted.
  2. descendingIterator(): Returns an iterator over the elements in the set in reverse order.

Here’s an example of how to use a LinkedHashSet:

Set<String> set = new LinkedHashSet<String>();

set.add("apple");
set.add("banana");
set.add("orange");
set.add("apple"); // This will not be added to the set

System.out.println(set.size()); // prints "3"

set.remove("banana");

System.out.println(set.contains("banana")); // prints "false"

In this example, we create a new LinkedHashSet and add four elements to it using the add() method. Since “apple” is already in the set, it is not added again. We then print the size of the set using the size() method, remove “banana” from the set using the remove() method, and check if the set contains “banana” using the contains() method. The elements in the set will be printed in the order in which they were inserted.

SortedSet Interface:

In Java, the SortedSet interface is a subtype of the Set interface and extends it to provide additional methods to handle sorted sets of elements. The SortedSet interface is implemented by several classes, including TreeSet, and defines the behavior of a set that is sorted in ascending order based on the natural ordering of its elements, or based on a custom comparator provided by the user.

The SortedSet interface has the following additional methods:

  1. comparator(): Returns the comparator used to order the elements in the set, or null if the natural ordering of the elements is used.
  2. first(): Returns the first (lowest) element in the set.
  3. last(): Returns the last (highest) element in the set.
  4. headSet(E toElement): Returns a view of the portion of the set whose elements are less than toElement.
  5. tailSet(E fromElement): Returns a view of the portion of the set whose elements are greater than or equal to fromElement.
  6. subSet(E fromElement, E toElement): Returns a view of the portion of the set whose elements range from fromElement (inclusive) to toElement (exclusive).

Here’s an example of how to use a SortedSet:

SortedSet<Integer> set = new TreeSet<Integer>();

set.add(3);
set.add(1);
set.add(2);

System.out.println(set); // prints "[1, 2, 3]"

System.out.println(set.first()); // prints "1"

System.out.println(set.last()); // prints "3"

SortedSet<Integer> subSet = set.subSet(2, 3);

System.out.println(subSet); // prints "[2]"

In this example, we create a new TreeSet and add three elements to it using the add() method. Since TreeSet implements SortedSet, the elements are automatically sorted in ascending order. We then print the set using the System.out.println() method, which uses the toString() method to print the elements in the set. We also use the first() and last() methods to print the first and last elements in the set, and the subSet() method to create a subset of the set containing the elements whose values range from 2 (inclusive) to 3 (exclusive).

TreeSet:

In Java, TreeSet is a class that implements the SortedSet interface and provides a sorted set of elements stored in a tree-like data structure. The elements are sorted according to their natural ordering or using a custom comparator provided by the user.

TreeSet provides guaranteed log(n) time cost for the basic operations (add, remove and contains). Like all Set implementations, TreeSet does not allow duplicate elements.

TreeSet provides a number of useful methods, including:

  1. add(E e): Adds the specified element to the set if it is not already present.
  2. clear(): Removes all of the elements from the set.
  3. contains(Object o): Returns true if the set contains the specified element.
  4. first(): Returns the first (lowest) element currently in the set.
  5. last(): Returns the last (highest) element currently in the set.
  6. pollFirst(): Removes and returns the first (lowest) element, or null if the set is empty.
  7. pollLast(): Removes and returns the last (highest) element, or null if the set is empty.
  8. size(): Returns the number of elements in the set.
  9. subSet(E fromElement, E toElement): Returns a view of the portion of the set whose elements range from fromElement (inclusive) to toElement (exclusive).

Here’s an example of how to use a TreeSet:

TreeSet<Integer> set = new TreeSet<Integer>();

set.add(3);
set.add(1);
set.add(2);

System.out.println(set); // prints "[1, 2, 3]"

System.out.println(set.first()); // prints "1"

System.out.println(set.last()); // prints "3"

TreeSet<Integer> subSet = (TreeSet<Integer>) set.subSet(2, 3);

System.out.println(subSet); // prints "[2]"

In this example, we create a new TreeSet and add three elements to it using the add() method. The elements are automatically sorted in ascending order. We then print the set using the System.out.println() method, which uses the toString() method to print the elements in the set. We also use the first() and last() methods to print the first and last elements in the set, and the subSet() method to create a subset of the set containing the elements whose values range from 2 (inclusive) to 3 (exclusive). Note that we need to cast the result of the subSet() method to a TreeSet in order to use its methods.