In this article, we will understand how to get the size of the collection. The Collection is a framework that provides architecture to store and manipulate the group of objects. Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion.
Below is a demonstration of the same −
Suppose our input is −
Input list: [100, 180, 250, 300]
The desired output would be −
The size of the list = 4
Algorithm
Step 1 - START Step 2 - Declare a list namely input_list. Step 3 - Define the values. Step 4 - Using the function size(), we get the size of the input_list. Step 5 - Display the result Step 6 - Stop
Example 1
Here, we bind all the operations together under the ‘main’ function.
import java.util.*;
public class Demo {
public static void main(String[] args){
List<Integer> input_list = new ArrayList<Integer>();
input_list.add(100);
input_list.add(180);
input_list.add(250);
input_list.add(300);
System.out.println("The list is defined as: " + input_list);
int list_size = input_list.size();
System.out.println("\nThe size of the list = " + list_size);
}
}Output
The list is defined as: [100, 180, 250, 300] The size of the list = 4
Example 2
Here, we encapsulate the operations into functions exhibiting object oriented programming.
import java.util.*;
public class Demo {
static void print_size(List<Integer> input_list){
int list_size = input_list.size();
System.out.println("\nThe size of the list = " + list_size);
}
public static void main(String[] args){
List<Integer> input_list = new ArrayList<Integer>();
input_list.add(100);
input_list.add(180);
input_list.add(250);
input_list.add(300);
System.out.println("The list is defined as: " + input_list);
print_size(input_list);
}
}Output
The list is defined as: [100, 180, 250, 300] The size of the list = 4