We are moved to new domain
Click -> www.ehowtonow.com
Sunday, 31 May 2015

How to get the size of Collection

Following example shows how to get the size of collection using collection.size() method in Java.

int java.util.List.size()
size
int size()
Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE. Specified by:
    size in interface Collection<E>
Returns:
    the number of elements in this list

int java.util.Set.size()
size

int size() 
Returns the number of elements in this set (its cardinality). If this set contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.Specified by: size in interface Collection<E>
Returns:
    the number of elements in this set (its cardinality)

int java.util.Map.size()
size

int size() 
Returns the number of key-value mappings in this map. If the map contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.
Returns:
    the number of key-value mappings in this map

Sample Program
SizeOfCollection.java
package com.javatutorialcorner.collection;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class SizeOfCollection {

 public static void main(String[] args) {
  String[] nameArray = new String[] { "Spring", "Struts", "Hibernate",
    "Webservice", "SOAP Webservice", "RESTful Webservice" };
  List<String> nameList = Arrays.asList(nameArray);
  System.out.println("List size " + nameList.size());

  Set<String> set = new HashSet<String>(nameList);
  System.out.println("Set size " + set.size());

  Map map = new HashMap();
  System.out.println("Map size " + map.size());

 }

}


Result
The above code will produce the following output.
List size 6
Set size 6
Map size 0

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: How to get the size of Collection Rating: 5 Reviewed By: eHowToNow