×

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

Zebra Puzzle Problem in Java

Complex puzzles like the zebra puzzle demand a lot of work and mental training to complete. Because it was created by renowned German scientist Albert Einstein, it is also sometimes...

10 minutes read.

Java ArraylistRemove() Time Complexity

In this tutorial, we will learn about how we can remove time complexity in Java ArrayList. But unless we will not learn what is ArrayList, we don’t understand this process....

7 minutes read.

Skyline Problem in Java

The skyline of a city is the outer edge of the pattern created by all of its structures when viewed from a distance. Return the skyline that these buildings together...

4 minutes read.

Java Public Keyword

A Java access modifier is a public keyword. It can be applied to classes, constructors, methods, and variables. It is the type of access modifier that is least constrained. A...

4 minutes read.

Tetris Game in Java

The Tetris game is among the most well-known video games ever produced for computers. Today, we may engage in this game on a mobile device as well. Alexey Pajitnov conceptualized...

12 minutes read.

Java array list remove time complexity

Java: We know that java is one of the programming languages. The main feature of java which is not in C or object oriented programming language is platform independence. Not only the...

7 minutes read.

Java finally

Java finally: There are some statements in a program whose execution is extremely important. For example, closing of a database connection. Statements that do the closing of the database connection...

5 minutes read.

Java Integer parseUnsignedInt() method

The parseUnsignedInt() method of Java Integer class parses the string argument as an unsigned decimal integer. The second parameter parses the string argument as an unsigned integer in the radix specified...

2 minutes read.

Java Do While Loop

When we wish to test the exit condition at the end of the loop, we use a do-while loop. The do-while loop always executes its body at least once, because...

1 minute read.

Java Stringjoiner Class

StringJoiner is a class which is used to construct a sequence of characters which are separated by a delimiter. Optionally, it starts with a provided prefix and ended with the...

5 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 take String Input in Java

There are various ways to take String input in Java. In this section, we are going to discuss how to take String input in Java. There are following ways to...

5 minutes read.

Decagonal Numbers in Java

This section explains what is a decagonal number and how to write Java programmes that compute decagonal numbers. Both academics and Java programmer interviews regularly question about the Decagonal number...

3 minutes read.

Economical number in Java

Economical number is said to be economically efficient if the number of digits after prime factorization of the original number with their powers is less than the number of digits...

3 minutes read.

Java ResultSetMetaData

The data about another data is called Metadata. The ResultSetMetaData is used to store the data about ResultSet. The ResultSet Contains the columns, rows, names of table, datatypes etc. these...

2 minutes read.

Java HashSet

HashSet implements the set interface. It uses the hash table to make the collection to store different data types. The hash set is the unordered collection of different data types....

6 minutes read.

Check whether Java is installed or not

As we know that there are various operating systems, to check whether Java is installed or not in Windows and Mac we use the following ways.           Windows Operating System: There are several...

2 minutes read.

Constructor Chaining and Constructor Overloading in Java

Constructor Chaining Constructor chaining and constructor overloading are two confusing terms. Let's first understand constructor chaining.Constructor chaining is the process of calling one constructor from another constructor using the same object....

2 minutes read.

How to Convert String to long in Java

How to Convert String to long in java It is used when you want to perform the mathematical operation on the String which contains long number then the conversion from String...

4 minutes read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.