JavaRush /Java Blog /Random EN /Coffee break #185. A Comprehensive Guide to the Java Coll...

Coffee break #185. A Comprehensive Guide to the Java Collection Framework

Published in the Random EN group
Source: Medium This tutorial will help you better understand the workings of the various classes and interfaces included in the Java Collection Framework. Coffee break #185.  A Comprehensive Guide to the Java Collection Framework - 1Java Collection is a framework that provides a unified architecture for storing and managing a group of objects. At its core, it is a set of classes and interfaces that provide a standard way to represent and manipulate collections of objects in the Java language. The framework also helps in implementing commonly used data structures such as List, Set and Map. The Java Collection Framework includes several interfaces and classes. Here is a list of some of them:

Interfaces

Interfaces in the Java Collection Framework define the general behavior and operations that can be performed on collections. This includes adding or removing items, repeating items in a collection, and more.
  • Collection : The root interface in a collection hierarchy, representing a group of objects known as elements.
  • List : An ordered collection of elements that allows duplication.
  • Set : a collection of elements that do not allow duplication.
  • Map : a collection of key-value pairs, where each key is unique.
  • Queue : A queue is a data structure that is used to store elements in First-In-First-Out (FIFO).
This list does not include everything, but only the most used interfaces in the Java Collection Framework. Now let's take a closer look at each of them.

Collection

A Collection is a group of objects known as its elements. This is an object that can contain references to other objects. The Collection interface is the root of the collection hierarchy. This is the base interface for all collections in the Java Collection Framework. It defines the basic methods that must be implemented in all collections, such as add() , remove() and contains() . Here is an example of using collections in the Java Collection Framework. Here the Collection interface is used to add and remove elements from a collection:
import java.util.Collection;
import java.util.ArrayList;

public class CollectionExample {
    public static void main(String[] args) {
        // Создаем новую коллекцию
        Collection<String> stringCollection = new ArrayList<>();

        // Добавляем несколько элементов в коллекцию
        stringCollection.add("hello");
        stringCollection.add("world");
        stringCollection.add("foo");
        stringCollection.add("bar");

        // Печатаем число элементов в коллекции
        System.out.println("Number of elements: " + stringCollection.size());

        // Удаляем элемент из коллекции
        stringCollection.remove("foo");

        // Опять печатаем число элементов в коллекции
        System.out.println("Number of elements: " + stringCollection.size());
    }
}
The output is:
Number of elements: 4 Number of elements: 3
As you can see, the Collection interface is a simple and convenient way to perform common operations with a collection of objects. It is often used as a starting point when working with collections in Java. The Java Collection Framework includes several interfaces that define common behavior for different types of collections. Some of them are part of the java.util.Collection interface group :
  • java.util.List
  • java.util.set
  • java.util.Queue

java.util.List

List is an ordered collection of objects, each element of which occupies a specific position in the list. The List interface extends the Collection interface and adds several methods for working with lists, such as methods for accessing elements by their position in the list and methods for searching and sorting lists. A List can contain duplicate elements , these elements can be accessed by their position in the list. Here's an example of using the List interface to add, remove, and access items in a list:
import java.util.List;
import java.util.ArrayList;

public class ListExample {
    public static void main(String[] args) {
        // Создаем новый список
        List<String> stringList = new ArrayList<>();

        // Добавляем несколько элементов в список
        stringList.add("India");
        stringList.add("UAE");
        stringList.add("London");
        stringList.add("US");

        // Печатаем первый элемент в списке
        System.out.println("First element: " + stringList.get(0));

        // Удаляем второй элемент из списка
        stringList.remove(1);

        // Печатаем второй элемент в списке
        System.out.println("Second element: " + stringList.get(1));
    }
}
Conclusion:
First element: India Second element: London
As shown above, the List interface provides a convenient way to work with ordered collections of elements. It is typically used when you need to maintain the order of elements in a collection or when you need to access elements by their index in a list.

java.util.Set

A Set in the Java Collection Framework is an unordered set of unique elements that does not allow duplicate elements . The Set interface extends the Collection interface and adds several methods, such as methods for checking whether an element is in a set and methods for adding and removing elements from a set. Here is an example of using the Set interface to add and remove elements from a set in the Java Collection Framework:
import java.util.Set;
import java.util.HashSet;

public class SetExample {
    public static void main(String[] args) {
        // Создаем новый set
        Set<String> stringSet = new HashSet<>();

        // Добавляем несколько элементов в set
        stringSet.add("Jan");
        stringSet.add("Feb");
        stringSet.add("March");
        stringSet.add("April");

        // Проверяем наличие в set element "March"
        if (stringSet.contains("March")) {
            System.out.println("The set contains the element 'March'");
        }

        // Удаляем элемент "April" из set
        stringSet.remove("April");

        // Опять проверяем наличие element "April" в set
        if (!stringSet.contains("April")) {
            System.out.println("The set no longer contains the element 'April'");
        }
    }
}
Conclusion:
The set contains the element 'March' The set no longer contains the element 'April'

java.util.Queue

A Queue is a data structure that is used to store elements in first-in-first-out (FIFO) order. This means that the first element added to the queue will be the first element removed. Here is an example of how to use a queue in the Java Collection Framework:
// Creation очереди
Queue<String> queue = new LinkedList<>();

// Добавление элементов в очередь
queue.add("apple");
queue.add("banana");
queue.add("orange");
// Печатаем очередь
System.out.println("Queue: " + queue);
// Удаляем элемент из очереди
String element = queue.remove();
System.out.println("Removed element: " + element);
// Печатаем обновленную очередь
System.out.println("Queue: " + queue);
In this example, we created a string queue and added three elements to it: “apple”, “banana” and “orange”. We then print the queue to see its current state. Next, we remove the element from the queue and print it to the console. Finally, we print the updated queue to ensure that the removed element is no longer in the queue.

Map

The java.util.Map interface in the Java Collection Framework is used to map keys to values. It allows you to store elements as key-value pairs and provides methods for accessing, modifying, and iterating on elements in a map. Below is an example of using the Map interface :
// Создаем Map
 Map<String, Integer> map = new  HashMap <>();
// Добавляем элементы в Map
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
// Печать Map
 System.out.println("Map: " + map);
// Получаем meaning для определенного ключа
int  value  = map.get( "banana" );
System.out.println("Value for 'banana': " + value);
// Удаляем элемент из Map
map.remove("orange");
// Печать обновленной карты
 System.out.println( "Map: " + map);
In this example, we create a map of strings and integers by adding three elements to it: “apple” maps to 1, “banana” maps to 2, and “orange” maps to 3. We then print the map to see its current meaning. After that, we get the value of the “banana” key and print it to the console. Finally, we remove the key-value pair for “orange” from the map and print the updated map to see that the removed element is no longer there.

Classes

A Class is a concrete implementation of a collection interface. It provides specific implementations of common behaviors and operations defined by interfaces in the framework.
  • ArrayList : An implementation of the List interface with a resizable array.
  • LinkedList : a doubly linked list, an implementation of the List and Deque interfaces .
  • HashSet : An implementation of Set that uses a hash table for storage.
  • TreeSet : An implementation of Set that uses a tree for storage.
  • HashMap : An implementation of Map that uses a hash table for storage.
The above list is one of the most commonly used classes in the Java Collection Framework. Now let's look at the detailed explanation of these classes.

ArrayList

The java.util.ArrayList class in Java collections is used to store a resizable array of elements in a list. It is a widely used implementation of the java.util.List interface that uses an array to store elements and provides efficient methods for accessing, modifying, and iterating through elements in a list. The java.util.ArrayList class provides fast random access to its elements, but slow insertion and removal at random positions. Below is an example of using ArrayList class in Java Collection Framework:
// Создаем array list
List<String> list = new ArrayList<>();
// Добавляем элементы в array list
list.add("qa");
list.add("devops");
list.add("dev");
// Печатаем array list
System.out.println("Array list: " + list);
// Доступ к элементу по определенному индексу
String element = list.get(1);
System.out.println("Element at index 1: " + element);
// Удаление element из the array list
list.remove(1);
// Print the updated array list
System.out.println("Array list: " + list);
As you can see, we created an array of strings and added three elements to it: “qa”, “devops” and “dev”. We then printed the array list to see its current state. After this, we access the element at index 1 and print it to the console. Finally, we remove the element at index 1 from the array list and print an updated array list to ensure that the removed element is no longer in the list.

LinkedList

The java.util.LinkedList class in the Java Collection Framework inherits from the AbstractList class and implements the List and Deque interfaces . It provides efficient methods for adding, removing, and accessing elements at the beginning and end of a list. This Class is also an implementation of the List interface , which uses a doubly-linked list to store elements. It provides fast insertion and deletion at arbitrary positions, but slow random access to its elements. Here is an example of how to use the LinkedList class in the Java Collection Framework:
// Создаем linked list
List<String> list = new LinkedList<>();
// Добавляем элементы в linked list
list.add("selenium");
list.add("cypress");
list.add("playwright");
// Печатаем linked list
System.out.println("Linked list: " + list);
// Добавляем элемент в начало списка
list.add(0, "webdriver.io");
// Печатаем обновленный linked list
System.out.println("Linked list: " + list);
// Удаляем первый элемент в списке
list.remove(0);
// Еще раз печатаем обновленный linked list
System.out.println("Linked list: " + list);
In this example, we created a linked list of strings and added three elements to it: “selenium”, “cypress” and “playwright”. We then print the linked list to see its current state. Next, we add the element “webdriver.io” to the beginning of the list and print the updated linked list. Finally, we remove the first element from the list and print the updated linked list again to see that the deleted element is no longer in the list.

HashSet

The java.util.HashSet class in the Java Collection Framework is used to store a collection of unique elements in a set. It provides a hash table-based implementation of the java.util.Set interface. It also provides fast insertion, deletion and search, but does not preserve the order of its elements. Below is an example of using the HashSet class in the Java Collection Framework:
// Создаем hash set
Set<String> set = new HashSet<>();

// Добавляем элементы в hash set
set.add("rose");
set.add("lily");
set.add("lotus");
// Попытка добавить повторяющийся элемент
set.add("rose");
// Печатаем hash set
System.out.println("Hash set: " + set);
// Удаляем элемент из hash set
set.remove("lily");
// Печать обновленного hash set
System.out.println("Hash set: " + set);
Here we created a hash set of strings and added three elements to it: “rose”, “lily” and “lotus”. We then try to add the element “rose” again, but since the hash set does not allow duplicates, it will not be added. After this we print the hash set to see its current state. We then remove the element “lily” from the set and print the updated hash of the set to see that the removed element is no longer in the set.

TreeSet

The java.util.TreeSet class in the Java Collection Framework is used to store a collection of unique elements in a set sorted in ascending order. It provides a tree-based implementation of the java.util.Set interface to store elements without allowing duplicate elements. The class provides fast insertion, deletion, and searching, and maintains the order of its elements according to their natural order or comparator. Here is an example of how to use the TreeSet class in the Java Collection Framework:
// Создаем tree set
Set<String> set = new TreeSet<>();

// Добавляем элементы в tree set
set.add("apple");
set.add("banana");
set.add("orange");
// Попытка добавить повторяющийся элемент
set.add("apple");
// Печатаем tree set
System.out.println("Tree set: " + set);
// Удаляем элемент из tree set
set.remove("banana");
// Печатаем обновленный tree set
System.out.println("Tree set: " + set);
In this example, we create a tree set of strings and add three elements to it: “apple”, “banana” and “orange”. We then try to add the “apple” element again, but since the tree set does not allow duplicates, it will not be added. After this we print the tree set to see its current state. Since the tree set is sorted in ascending order, the elements will be printed in the order: “apple”, “banana” and “orange”. We then remove the element “banana” from the set and print the updated tree set to see that the removed element is no longer in the set.

HashMap

The java.util.HashMap class in the Java Collection Framework is used to store the mapping of keys to values ​​in a map. It provides a hash table-based implementation of the java.util.Map interface and allows elements to be stored as key-value pairs. The class provides fast insertion, deletion, and search, but does not preserve the order of its elements. Here is an example of how to use the HashMap class in the Java Collection Framework:
// Создаем hash map
Map<String, Integer> map = new HashMap<>();

// Добавляем элементы в hash map
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
// Печатаем hash map
System.out.println("Hash map: " + map);
// Получаем meaning для определенного ключа
int value = map.get("banana");
System.out.println("Value for 'banana': " + value);
// Удаляем элемент из hash map
map.remove("orange");
// Печатаем обновленный hash map
System.out.println("Hash map: " + map);
In this example, we create a hash map of integer strings and add three elements to it: “apple” matches 1, “banana” matches 2, and “orange” matches 3. We then print the hash map to see it Current state. After that, we get the value of the “banana” key and print it to the console. Finally, we remove the key-value pair for “orange” from the hash map and print the updated hash map to see that the removed element is no longer in it.

Conclusion

The Java Collection Framework is a set of classes and interfaces that provide a standard way to represent and manipulate collections of objects in the Java programming language. This allows developers/testers to work with collections of objects in a consistent and efficient manner. The framework provides them with methods to store, access, and manage items in a collection, and allows them to easily switch between different collection implementations depending on the application's requirements.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION