Java Program to Get the Size of the Collection

JavaCampus InterviewServer Side ProgrammingProgramming

<p>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.</p><p>Below is a demonstration of the same &minus;</p><p><strong>Suppose our input is</strong> &minus;</p><pre class="result notranslate">Input list: [100, 180, 250, 300]</pre><p><strong>The desired output would be</strong> &minus;</p><pre class="result notranslate">The size of the list = 4</pre><h2>Algorithm</h2><pre class="result notranslate">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</pre><h2>Example 1</h2><p>Here, we bind all the operations together under the &lsquo;main&rsquo; function.</p><pre class="demo-code notranslate language-java" data-lang="java">import java.util.*; public class Demo { &nbsp; &nbsp;public static void main(String[] args){ &nbsp; &nbsp; &nbsp; List&lt;Integer&gt; input_list = new ArrayList&lt;Integer&gt;(); &nbsp; &nbsp; &nbsp; input_list.add(100); &nbsp; &nbsp; &nbsp; input_list.add(180); &nbsp; &nbsp; &nbsp; input_list.add(250); &nbsp; &nbsp; &nbsp; input_list.add(300); &nbsp; &nbsp; &nbsp; System.out.println(&quot;The list is defined as: &quot; + input_list); &nbsp; &nbsp; &nbsp; int list_size = input_list.size(); &nbsp; &nbsp; &nbsp; System.out.println(&quot; The size of the list = &quot; + list_size); &nbsp; &nbsp;} }</pre><h2>Output</h2><pre class="result notranslate">The list is defined as: [100, 180, 250, 300] The size of the list = 4</pre><h2>Example 2</h2><p>Here, we encapsulate the operations into functions exhibiting object oriented programming.</p><pre class="demo-code notranslate language-java" data-lang="java">import java.util.*; public class Demo { &nbsp; &nbsp;static void print_size(List&lt;Integer&gt; input_list){ &nbsp; &nbsp; &nbsp; int list_size = input_list.size(); &nbsp; &nbsp; &nbsp; System.out.println(&quot; The size of the list = &quot; + list_size); &nbsp; &nbsp;} &nbsp; &nbsp;public static void main(String[] args){ &nbsp; &nbsp; &nbsp; List&lt;Integer&gt; input_list = new ArrayList&lt;Integer&gt;(); &nbsp; &nbsp; &nbsp; input_list.add(100); &nbsp; &nbsp; &nbsp; input_list.add(180); &nbsp; &nbsp; &nbsp; input_list.add(250); &nbsp; &nbsp; &nbsp; input_list.add(300); &nbsp; &nbsp; &nbsp; System.out.println(&quot;The list is defined as: &quot; + input_list); &nbsp; &nbsp; &nbsp; print_size(input_list); &nbsp; &nbsp;} }</pre><h2>Output</h2><pre class="result notranslate">The list is defined as: [100, 180, 250, 300] The size of the list = 4</pre>
raja
Updated on 30-Mar-2022 06:31:33

Advertisements