×

Collection Programs in Java

Collection Programs in Java

Collection in Java provides a way to manipulate or store a group of objects. Each object in a collection is called element. Collection programs in Java mainly deals with the Java collection framework that provides various interfaces, classes that is used to implement different types of data structures and algorithms. For example, the implementation of doubly linked list is done by the class LinkedList of the collection framework.

Interfaces of Collection Framework

There are various interfaces that are integral part of the Collection Framework. Some of the interfaces that form the core of the Collection Framework are:

1) Iterable Interface: It is the root interface of collection framework hierarchy. This interface provides iterators for the collection elements. These iterators are very handy when traversal of elements is required.

2) Collection Interface: It extends the Iterable interface. Other interfaces, List, Set, and Queue extends the collection interface. Collection interface renders all the basic methods that are required by a collection element. In collection framework, no class directly implements this interface. This framework provides the foundation upon which the collection framework relies a lot.

3) List Interface: It is used to provide elements in ordered manner. Using this interface, one can add, remove, and update elements from the list. Elements can be inserted or accessed by their position in the list. Using List interface, it is possible to create dynamic lists, i.e., those lists whose size can be update during run-time. LinkedList, ArrayList, Vector, Stack are the classes that implement the List interface.

4) Set Interface: Set interface is similar to sets that we have learnt in Mathematics. Similar to mathematics, duplicate elements are not allowed in Set interface. TreeSet and LinkedHashSet are the classes that implement this interface.

5) Queue Interface: The queue interface provides the features of queue data structure. This means, elements of the classes that implement Queue Interface, are stored in First In First Out (FIFO) manner. Classes that implement this interface are ArrayDeque, PriorityQueue.

6) Map Interface: It does not extend the Iterable interface. This interface is another root of the collection framework. Objects of the class implementing the Map interface always store association between keys and values, i.e. it maintains key/ value pair. Note that the key, in the key/ value pair, has to be unique. However, duplicates values are allowed. TreeMap and HashMap are the classes that provide the implementation of the Map interface.

Methods of the Collection Interface

The Collection Interface provides core methods that all collections will have.

MethodsDescription
public boolean add(Object o)for adding an element
public static boolean addAll(Collection c)Add the collection c to the given collection
public boolean remove(Object o)remove the object o.
public boolean removeAll(Collection c)Remove the collection C from the given collection
public boolean retainAll(Collection c)All the elements of the collection c get retained, while others get deleted.
public int size()returns size of the collection
public void clear()remove all elements from the collection
public boolean contains(Object o)Checks if the object o is present in the collection or not.
public boolean containsAll(Collection c)Checks whether the collection c is present in the collection or not.
public boolean isEmpty()Checks if the collection is empty or not.
public Iterator iterator()Returns an iterator for the collection.
public Object[] to arrayConverts the collection into array.
Object[] toArray(Object arr[])Returns an array whose type matches with the array arr.
public int hashCode()for returning the hash code number of the collection.
public boolean equals(Object o)compares the object o with the object that invokes this method.

Note: The last two methods are of the Object class.

Significance of the Collection Framework

1) This framework provides various algorithm and data structures that can be used directly in the code. Thus, we do not need to implement those data structures or algorithms manually. For example, for storing unique element only set interface can be use. For storing elements in ordered way, array list or linked list can be used.

2) Collection framework is highly optimized. Thus, the code written using this framework is highly efficient.

Let’s see an example of Collection.

CollectionExample.java

 import java.util.*;  
class CollectionExample.java
{  
public static void main(String args[]){  
ArrayList<String> list=new ArrayList<String>();//Creating arraylist  
list.add("Norway");//Adding object in arraylist  
list.add("Atlanta");  
list.add("Czech Republic");  
list.add("Santa Clara");  
//Traversing list through Iterator  
Iterator itr=list.iterator();  
while(itr.hasNext()){  
System.out.println(itr.next());  
}  
}  
}   

Output:

 Norway
Atlanta
Czech Republic
Santa Calara 

Related Topics

Java Int Keyword

Among the primitive data types is the Java int keyword. To declare variables, use this. It can also be used with methods that return values of the integer type. It...

3 minutes read.

Java vs Scala

Java : Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say...

4 minutes read.

Types of Garbage Collector in Java

Garbage collection is a Java feature that offers automatic memory management. The JVM is in charge of it. The programmer does not have to handle object creation and deallocation. We...

3 minutes read.

Dining Philosophers problem in Java

The Problem of the Dining Philosophers illustrates a concurrency issue involving the distribution of scarce resources among conflicting processes. Problem Statement Imagine a dining table with a circle in the middle and five...

3 minutes read.

Java Garbage Collection

Java Garbage Collection In Java, unreferenced objects are treated like garbage. The process of reclaiming the unused memory during runtime automatically is known as the Java Garbage Collection.In other words, the...

4 minutes read.

Java Math log() Method

The log() method of Math class returns the natural logarithmic value for the specified double argument. Syntax: public static double log(double a) Parameters: The parameter ‘a’ represents the value. Return Value: The log() method returns the...

1 minute read.

How to Convert double to int in Java

The double is a larger data type than int. When we assign a larger type value to a variable of smaller type, then we need to perform the explicit conversion....

2 minutes read.

Java 16

Java 16 is the most recent short-term incremental release, based on Java 15, and it was released on March 16, 2021. Records and sealed classes are just two of the...

11 minutes read.

Java String Interview Questions

Java String Interview Questions String is the most common and important discussed topics in a Java interview. In Java interview interviewer generally asked three to four questions based on String concept....

16 minutes read.

Java Command Line Arguments

Java command line arguments Command line argument is an input or argument to the program when you run the program. In Java, we can take the inputs from the console, and...

2 minutes read.

Java Technologies List

Introducing Java technology is not necessary. Everyone across the globe is still in awe of Java's incredible capabilities for developing mobile apps and websites. Of course, you can be persuaded...

8 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.

Constructor Program in Java

Constructor Program in Java In Java, a constructor is a piece of code that is used to create an object. A constructor is called implicitly when an object is created in...

7 minutes read.

Java String replaceAll() method

Java String replaceAll() method returns a String replacing all the sequence of characters matching regular expression i.e regex and replacement string. Syntax: public String replaceAll(String regex, String replacement) Parameters: regex : regular expression replacement :...

1 minute read.

Difference Between BufferedReader and FileReader

BufferedReader: To read data from a specified character stream, two classes are used: buffered readers and file readers. Both of them have advantages and disadvantages. Although how they operate is the...

6 minutes read.

Java Math nextDown() Method

The nextDown() method of Math class returns the floating-point number adjacent to the argument in direction of the negative infinity. Syntax: public static double nextDown (double d)public static float nextDown (float f) Parameters: The...

2 minutes read.

How to Convert long to String in Java

How to Convert long to String in java It is used if we have to display a long number in the text field because everything is displayed as a String. A...

3 minutes read.

How to Convert Octal to Decimal in Java

How to Convert Octal to Decimal in Java There are two methods to convert Octal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method The Integer.parseInt() method is a static method...

2 minutes read.

Nth Term of Geometric Progression in Java

There are 3 numbers provided. The geometric progression's initial term is the first number. The second number is the geometric progression's common ratio, and the third number represents the nth...

3 minutes read.

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.