Skip to main content

Collection Framework in Java

Data Structure


As a definition, the data structure is a specific method of organizing data in a computer so that it may be used efficiently.
In this article, we are going to see about the Collection Framework which enables us to implement some important Data Structures available on Java.

Topics covered:
  ∘ Data Structure
  ∘ Collection Framework
  ∘ Class vs Interface
  ∘ Lists
  ∘ Set
  ∘ Map
  ∘ Difference between List, Set, and Map interface in Java

Collection Framework


A Java collection is a grouping of separate objects that are represented as a single entity. Java collections, like data, provide all actions such as searching, sorting, insertion, modification, deletion, and so on. Java Collections is a fairly broad topic, and as a newbie, it might be tough to find your way around. We’ve covered all you need to know to get started with Java Collections.
Image from https://www.geeksforgeeks.org/how-to-learn-java-collections-a-complete-guide/

What exactly is a framework in Java?


  1. It offers prefabricated architecture.
  2. It denotes a bundle of classes and interfaces.
  3. It is entirely optional.

What exactly is the Collection Framework?


The Collection framework is a coherent architecture for storing and manipulating a collection of items.

It has:

  1. Interfaces and their implementations, i.e., classes
  2. Algorithm

Class vs Interface

+------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------+
| Class | Interface |
+------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------+
| In Java, a class is a user-defined prototype for creating objects. | A user-defined interface is a blueprint that outlines the structure of any class that implements it. |
| It is used to specify the properties of objects. | It can't be used to define things. |
| The access modifiers public and default can be applied to a class. | The access modifiers public and default can be applied to an Interface. |
| Concrete and abstract classes are both possible. | The interfaces are all abstract. |
| Constructors, methods, and attributes make up a class. A class is used to specify the methods. | An interface is made up of characteristics and methods. An interface does not specify the methods; it just includes their signature. |
+------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------+

Lists


The Collection interface gives way to the List interface. A list’s components are arranged in sequential order. The user may access a specific element in the list by using the index number; in other words, the user has total control over which element is put where in the list.

ArrayList


The List interface is implemented by the ArrayList class. This class’s objects are dynamic arrays. The ArrayList is a resizable version of the List class. It implements all List methods and accepts all items, even null ones. The capacity of ArrayList objects is initially equal to the size, but it grows dynamically when additional components are added. An ArrayList is unsynchronized, which means it may be accessed by several threads at the same time. In the Operating System, a thread is a unit of sequential flow control that may be processed.

Syntax to create an integer type ArrayList;

ArrayList<Integer> intArrayList = new ArrayList<Integer>();

Let's see an implementation of ArrayList.

import java.util.*;
public class BasicArrayList {
// main method
public static void main(String[] args) {
ArrayList<Integer> intArr = new ArrayList<Integer>();
// Add elements using add() method
intArr.add(10);
intArr.add(12);
intArr.add(25);
intArr.add(19);
intArr.add(11);
intArr.add(3);
// Print the ArrayList on the console
System.out.println(intArr);
// Remove elements at index 1 and 4
intArr.remove(1);
intArr.remove(4);
// Print the ArrayList on the console
System.out.println(intArr);
// Check if intArr contains the element 25
if(intArr.contains(25))
{
System.out.println("The ArrayList contains 25");
}
else
{
System.out.println("No such element exists");
}
// Use get method to get the element at index 1
int elementAt1 = intArr.get(1);
System.out.println("The Element at index 1 now is " + elementAt1);
}
}

Set


The Set interface adds to the functionality of the Collection interface. The Set is a structure that represents a set’s mathematical definition. It depicts an unsorted group of elements that prevents us from storing duplicates. In Set, we can only save one null value. HashSet, LinkedHashSet, and TreeSet are all implementations of Set.
Let’s see the implementation of one of the implementations of Set due to a special property which we can see in the comparing part.

TreeSet


The Navigable interface is implemented by the TreeSet class. The TreeSet employs a tree structure to store components and a set to organize them, as the name implies. Natural ordering or order by the Comparator set at the time of building are the two options. Because the TreeSet is unsynchronized, we must synchronize it externally if many threads wish to access it at the same time.

Syntax to create an integer type TreeSet;

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

Let's see an implementation of TreeSet.

import java.util.*;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet<Integer> intTreeSet = new TreeSet<Integer>();
// Add elements using add()
intTreeSet.add(18);
intTreeSet.add(13);
intTreeSet.add(29);
intTreeSet.add(56);
intTreeSet.add(73);
// Try to add a duplicate
// Observe output as it will not be added
intTreeSet.add(18);
// Print the TreeSet on the console
System.out.println("The contents of intTreeSet : ");
System.out.println(intTreeSet);
// Remove 18 using remove()
if(intTreeSet.remove(18)) {
System.out.println("\nElement 18 has been removed");
} else {
System.out.println("\nNo such element exists");
}
// Try to remove a non-existent element
if(intTreeSet.remove(12)) {
System.out.println("\nElement 18 has been removed");
} else {
System.out.println("\nNo such element exists");
}
System.out.println();
// Print the TreeSet on the console
System.out.println("The contents of intTreeSet : ");
System.out.println(intTreeSet);
}
}

Map


The Map interface is a structure that associates each value with a key. Because one key cannot have multiple mappings, a Map does not allow duplicate items. A Map may be seen in three ways: as a Set of keys, a Set of key-value mappings, or as a Collection of values. The Map interface’s methods are listed below, and any class that implements Map must define these methods.

SortedMap


The SortedMap interface adds the need for a total order of keys to the Map interface. Depending on the constructor used, the keys are either sorted by natural ordering or by a Comparator given at the time of creation. The keys must all be comparable.

TreeMap


The SortedMap interface is implemented by the TreeMap class. The TreeMap class stores data in a red-black tree structure and orders the components using a map. Every element is a pair of keys and values. For fundamental operations, this solution guarantees a log(n) time cost.

Syntax to create a String type TreeMap;

TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();

Let's see an implementation of TreeMap.

import java.util.*;
public class TreeMapExample {
public static void main(String[] args) {
TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();
// Add elements using put()
treeMap.put(1, "This");
treeMap.put(2, "is");
treeMap.put(3, "TreeMap");
// Print the contents of treeMap on the console
System.out.println("The contents of treeMap : ");
System.out.println(treeMap);
// Add a duplicate key
treeMap.put(1, "Duplicate");
// Add a duplicate value
treeMap.put(4, "is");
// Print the contents of treeMap on the console
System.out.println("\nThe contents of treeMap after adding duplicates : ");
System.out.println(treeMap);
}
}

Difference between List, Set, and Map interface in Java


1 — Ordering
List — In Java, a list is an ordered sequence whose entries are accessed by an index.

Set — In Java, a set is a unique collection of items that can be sorted or unordered depending on the implementation. HashSet implementations, for example, are unordered, LinkedHashSet implementations are ordered, and TreeSet implementations are ordered by natural order or given comparator.

Map — In Java, a map represents the key-value mapping. Map’s ordering is likewise implementation-dependent. The TreeMap class, for example, is ordered, but the HashMap class is not.

2 — Duplicates
List — It is possible for elements in a list to be duplicated.

Set — Only distinct elements make up a set.

Map — A Map does not allow duplicate keys, which means that each key can only map to one value.

3 — Null values
List — There can be any number of null values in a list.

Set — There can only be one null element in a set.

Map — Although null may be used as both a key and a value in a Map, certain implementations do not allow null keys or values.

4 — Implementing classes
List — ArrayList and LinkedList are two of the most common List interface implementation classes.

Set — HashSet, TreeSet, and LinkedHashSet are examples of set interfaces.

Map — The HashMap, TreeMap, and LinkedHashMap classes are available through the Map interface.

5 — When to use List, Set, and Map?
List — When the insertion order of elements must be maintained, a List can be utilized.

Set — If we need to keep a collection free of duplicates, we may use a set.

Map — When the data involves key-value pairs and quick retrieval of a value based on a key is required, use a map.

6 — Index and elements
List — The get() function in the list may be used to retrieve an element at a certain index.

Set — The get method in Set does not return the elements at a specified index.

Map — The get method in the map does not return the entries at a specified index.

7 — Iterator
List — Listlterator is used to traverse the list items.

Set — Iterator is a tool for traversing a set of items.

Map — Through the use of a keyset, a value, and an entry set.


You may encounter questions during your interview as well. These are very basics in Data Structure. Make sure you are aware of all these things.

I hope this can help you. Share your thoughts too.

Comments

Popular posts from this blog

Hello World project in ROS on Windows 10

We've seen how to install ROS in Windows 10 in this article, this is the time to start programming. What is the very first thing we do once we setup a new Programming Language? Hello World !!! Lets see how to write Hello World in ROS on Windows machine. Before going into the programming, make sure you've installed Gedit on your Windows machine. You can get it from here. Also, setup the path for Gedit and restart your machine to ensure the path definition works. First open the ROS terminal and check for the working directory. We have to be in the catkin workspace. If you've already created it, go to that directory. Or else, create it like this. Create a src folder inside catkin_ws. Inside that newly created src folder, lets create a new package in it. The command to create a ROS package is as follows. >catkin_create_pkg [PACKAGE_NAME] [DEPENDENT_PACKAGE_1] ....[DEPENDENT_PACKAGE_N] ‘std_msgs’ and ‘roscpp’ were added as optional dependent packages...

SQL Joins

You’ll nearly always need to connect many tables if you want to extract anything useful out of data. A join clause in SQL joins columns from one or more tables into a new table, similar to a join operation in relational algebra. In this article, let’s see how the joins work in SQL. We are going to explore the following SQL Joins.   ∘ 1 — (INNER) JOIN   ∘ 2 — LEFT (OUTER) JOIN   ∘ 3 — RIGHT (OUTER) JOIN   ∘ 4 — FULL (OUTER) JOIN AND UNION   ∘ When to use it? Also, I’m going to use the following tables for the above-mentioned SQL Joins. 1 — (INNER) JOIN Returns records with values in both tables that are the same. Image from Author As long as the condition is met, the INNER JOIN keyword selects all rows from both tables. This keyword will produce a result-set by merging all rows from both tables that satisfy the criteria, i.e. the common field’s value will be the same. Syntax: SELECT table1.column1,table1.column2,table2.column1,…. FROM table1 INNER JOIN ...

Setting Up Java Development Kit in Windows 10 

How to Download, Install, and Setting Up JDK in Windows 10? What is JDK? The Java Development Kit (JDK) is a software development environment for creating applets and Java applications. JDK is an abbreviation for Java Development Kit. It is available for usage by Java developers on Windows, macOS, Solaris, and Linux. JDK assists them in writing and running Java programs. It is feasible to run multiple JDK versions on the same machine. But it's recommended to install Java on Windows 10 with the latest version. In this article, we are going to see how to set up JDK in Windows 10. Let’s divide the article into three parts.   ∘ 1 . Getting the latest JDK version for Windows 10   ∘ 2 . Installing JDK in Windows 10   ∘ 3. Setting up the environment for Java in Windows 10 Let’s see one by one. 1 . Getting the latest JDK version for Windows 10 1 — Download the latest version of JDK from here . Image by Author 2 — Select the needed setup file as per ...