Size of LinkedHashSet

Its very important to know the size of LinkedHashSet as it is required in most of the times while coding

We have size() method in LinkedHashSet class which helps us to determine the size of LinkedHashSet

Size is the number of elements in that LinkedHashSet

public int size()


Example :

  1. import java.util.*;
  2.  
  3. public class LinkedHashSetSize {
  4.       public static void main(String[] args) {
  5.       LinkedHashSet<Integer> lhs = new LinkedHashSet<Integer>();
  6.       lhs.add(14);
  7.       lhs.add(7);
  8.       lhs.add(21);
  9.       lhs.add(28);
  10.       lhs.add(35);
  11.       lhs.add(42);   
  12.       System.out.println("Initial Size of LinkedHashSet: "+lhs.size());
  13.       lhs.remove(35);
  14.       lhs.remove(42);
  15.       System.out.println("Size after removing 2 elements: "+lhs.size());
  16.       System.out.println("Final LinkedHashSet after removal of 2 elements: ");
  17.       for(int ele: lhs){
  18.            System.out.println(ele);
  19.         }
  20.     }
  21. }
import java.util.*;

public class LinkedHashSetSize {
      public static void main(String[] args) {
      LinkedHashSet<Integer> lhs = new LinkedHashSet<Integer>();
      lhs.add(14);
      lhs.add(7);
      lhs.add(21);
      lhs.add(28);
      lhs.add(35);
      lhs.add(42);	 
      System.out.println("Initial Size of LinkedHashSet: "+lhs.size());
      lhs.remove(35);
      lhs.remove(42);
      System.out.println("Size after removing 2 elements: "+lhs.size());
      System.out.println("Final LinkedHashSet after removal of 2 elements: ");
      for(int ele: lhs){
           System.out.println(ele);
        }
	}
}


Here Size just tells how many elements are present in the LinkedHashSet

Don’t get confuse size with capacity in the LinkedHashSet, we will talk about capacity separately

Just remember Size() returns number of elements present in LinkedHashSet

Remember size() is a method , not a variable in the LinkedHashSet class.

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on