JavaRush /Java Blog /Random EN /Coffee break #185. Detailed guide to Java Collection Fram...

Coffee break #185. Detailed guide to Java Collection Framework

Published in the Random EN group
Source: Medium This tutorial will help you better understand the various classes and interfaces that make up the Java Collection Framework. Coffee break #185.  Detailed Guide to 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 the implementation of 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 elements, repeating elements in a collection, and more.
  • Collection : The root interface in the collection hierarchy, representing a group of objects known as elements.
  • List : An ordered collection of elements that allows for duplication.
  • Set : A collection of non-duplicate elements.
  • Map : a collection of key-value pairs (key-value), where each key is unique.
  • Queue : A queue is a data structure that is used to store elements in order of appearance (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 members. 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 all collections must implement, such as add() , remove() , and contains() . Here is an example of using collections in 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());
    }
}
In the output we get:
Number of elements: 4 Number of elements: 3
As you can see, the Collection interface is a simple and convenient way to perform standard operations on 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 collection types. Some of them are in the java.util.Collection interface group :
  • java.util.List
  • java.util.set
  • java.util.Queue

java.util.List

List (list) is an ordered set of objects, each element of which occupies a certain 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. List can contain duplicate elements , these elements can be accessed by their position in the list. Here is an example of using the List interface to add, remove, and access elements 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 commonly 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 to it, such as methods for checking if an element is in a set (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

Queue (queue) is a data structure that is used to store elements in the order of their appearance (FIFO). This means that the first item added to the queue will be the first item 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 have created a queue of strings 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 make sure 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 elements in a map. The following is an example 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" is matched against 1, "banana" is matched against 2, and "orange" is matched against 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 an 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 concrete implementations of the common behaviors and operations defined by the interfaces in the framework.
  • ArrayList : A resizable array implementation of the List interface.
  • LinkedList : a doubly linked list, an implementation of the List and Deque interfaces .
  • HashSet : A Set implementation that uses a hash table for storage.
  • TreeSet : A Set implementation that uses a tree for storage.
  • HashMap : A Map implementation that uses a hash table for storage.
The above list is one of the most used classes in the Java Collection Framework. Now let's look at a 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 elements in a list. The java.util.ArrayList class provides fast random access to its elements, but slow insertion and removal at arbitrary positions. The following is an example using the ArrayList class in the 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 have 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 that, 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 the updated array list to make sure the removed element is no longer in the list.

LinkedList

The java.util.LinkedList class in the Java Collection Framework inherits 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. Also, this Class is an implementation of the List interface , which uses a doubly-linked list to store elements. It provides fast insertion and removal 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 have 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 "webdriver.io" element to the top 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 removed 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 searching, but does not preserve the order of its elements. The following is an example 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 have created a hash set of strings and added three elements to it: “rose”, “lily”, and “lotus”. We then try to add the "rose" element again, but since the hash set does not allow duplicates, it will not be added. After that, we print the hash set to see its current state. We then remove the "lily" element 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 implementation of the java.util.Set interface to store elements without allowing duplicate elements. The class provides fast insertion, removal, and lookup 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 rowset 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 duplication, it will not be added. After that, we print 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 "banana" element 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 searching, 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" is matched against 1, "banana" is matched against 2, and "orange" is matched against 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 hashmap and print the updated hashmap 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 for storing, accessing, and manipulating the elements in a collection, as well as allowing them to easily switch between different collection implementations depending on the requirements of the application.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION