Friday, April 11, 2014

What is Collections and What are the different collections in Apex?

The Apex supports arrays to store data. Arrays are of a fixed
size which is defined during initialization of the array.

Developer typically require a data structure which is
flexible in size, so that they can add and remove items from this data
structure on request. To avoid that every developer has to implement his custom
data structure the Apex library provide several default implementations for
this via the collection.

Apex collections are dynamic in size, e.g. a collection
can contain a flexible number of objects.

More theoretical said, collection is a data structure which
contains and processes a set of data. The data stored in the collection is
encapsulated and the access to the data is only possible via predefined methods.

For example if your application saves data in an object of
type People, you can store several People objects in a collection.

Arrays and collections are a family of data types that
contain a sequence of values . It includes Lists , Arrays, Sets, and Maps.

Each collection type is different, but there are four methods
you can invoke on all of them:

1. clear: Removes all elements from the collection.

2. clone: Returns a copy of the collection.

3. isEmpty: Returns false if the collection has elements,
true if empty.

4. size: Returns the number of elements in the collection as
an Integer.

Array

array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but
it is often more useful to think of an array as a collection of variables of
the same type.

Instead of declaring individual variables, such as number0,
number1, ..., and number99, you declare one array variable such as numbers and
use numbers[0], numbers[1], and ..., numbers[99] to represent individual
variables.

Declaring Array Variables:

To use an array in a program, you must declare a variable to
reference the array, and you must specify the type of array the variable can
reference. Here is the syntax for declaring an array variable:

dataType[] arrayRefVar; // preferred way.

EX:-

Account[]
accs = new Account[]{};

Account a
= new Account();

a.name =
'xxx';

accs.add(a);

System.debug(accs[0].name);

a.clear();

System.debug(accs[0].name);

List

A list is an ordered collection of typed primitives,
sObjects, user-defined objects, Apex objects or collections that are
distinguished by their indices.

To declare a list, use the List keyword followed by the
primitive data, sObject, nested list, map, or set type within <>
characters.

deepClone(Boolean, Boolean, Boolean) :Makes a duplicate copy of
a list of sObject records, including the sObject records themselves.

equals(List)
:Compares
this list with the specified list and returnstrueif both lists are equal; otherwise, returnsfalse.

get(Integer) :Returns the list element
stored at the specified index.

getSObjectType()
:Returns
the token of the sObject type that makes up a list of sObjects.

hashCode() :Returns
the hashcode corresponding to this list and its contents.

isEmpty() :Returns
true if the list has zero elements.

iterator()
:Returns
an instance of an iterator for this list.

remove(Integer) :Removes
the list element stored at the specified index, returning the element that was
removed.

set(Integer, Object) :Sets the
specified value for the element at the given index.

size() :Returns
the number of elements in the list.

sort() :Sorts the items in the
list in ascending order.

public
class arrayListTest {

//creating List

List<String> nameList = new List<String>();

public void addElementsList(){

//Adding string objects to List

nameList.add('Jwalant');

nameList.add('Hiren');

nameList.add('Piyush');

nameList.add('Yogesh');

nameList.add('Dharmendra');

nameList.add('Piyush');

system.debug(‘List
size is-->’+ nameList.size());

//iterating over list

for(String name : nameList){

System.debug('List Elements is-->'+name);

}

}

}

addAll method Example

public
class arrayListAddAllTest {

public static void addAlltest() {

//creating List

List<String> firstList = new List<String>();

//Adding string objects to first List

firstList.add('Jwalant');

firstList.add('Hiren');

firstList.add('Piyush');

system.debug(‘
First List size is-->’+ firstList.size());

//creating ArrayList

List<String> secondList = new List<String>();

//Adding string objects to second List

secondList.add('Yogesh');

secondList.add('Dharmendra');

secondList.add('Piyush');

//add all objects of first list to second list.

secondList.addAll(firstList);

//iterating over second arraylist

for(String name : secondList){

System.debug('Second List Details is-->'+name);

}

}

public static void removeTest() {

//creating List

List<String> firstList = new List<String>();

//Adding string objects to first List

firstList.add('Jwalant');

firstList.add('Hiren');

firstList.add('Piyush');

firstList.remove(2); //remove 2nd position value.

//iterating over second list

for(String name : firstList){

System.debug(name);

}

}

}

Set

A set is an unordered collection of elements that do not contain any
duplicates. Set elements can be of any data type—primitive types, collections,
sObjects, user-defined types and built-in Apex types.

To declare a set, use the Set keyword followed by the
primitive data type name within <> characters. For example:

Set<String>
s1 = new Set<String>{'a', 'b + c'}; // Defines a new set with two elements

Set<String>
s2 = new Set<String>(s1); // Defines a new set that contains the

//
elements of the set created in the previous step

The following are instance methods for Set.

add(Object)
:Adds an
element to the set if it is not already present.

addAll(List<Object>)
:Adds all
of the elements in the specified list to the set if they are not already
present.

addAll(Set<Object>)
:Adds all
of the elements in the specified set to the set that calls the method if they
are not already present.

clear() :Removes all of the elements from the set

clone() :Makes a duplicate copy of
the set.

contains(Object)
:Returnstrueif the set contains the specified element.

containsAll(List<Object>)
:Returnstrueif the set contains all of the elements in
the specified list. The list must be of the same type as the set that calls the
method.

containsAll(Set<Object>)
:Returnstrueif the set contains all of the elements in
the specified set. The specified set must be of the same type as the original
set that calls the method.

equals(Set<Object>)
:Compares
this set with the specified set and returnstrueif both sets are equal; otherwise, returnsfalse.

hashCode()
:Returns
the hashcode corresponding to this set and its contents.

isEmpty()
:Returnstrueif the set has zero elements.

remove(Object)
:Removes
the specified element from the set if it is present.

removeAll(List<Object>)
:Removes
the elements in the specified list from the set if they are present.

removeAll(Set<Object>)
:Removes
the elements in the specified set from the original set if they are present.

retainAll(List<Object>)
:Retains
only the elements in this set that are contained in the specified list.

retainAll(Set)
:Retains
only the elements in the original set that are contained in the specified set.

size() :Returns the number of elements in the set
(its cardinality).

public
class SetExample {

public
static void setAdd() {

Set<String> countries = new Set<String>();

boolean result = false;

result = countries.add('USA');

System.debug('USA Added '+result);

result = countries.add('CANADA');

System.debug('CANADA Added '+result);

result = countries.add('U.K.');

System.debug('U.K. Added '+result);

result = countries.add('INDIA');

System.debug('INDIA Added '+result);

result = countries.add('CANADA');

System.debug('CANADA Added '+result);

System.debug('Size of set '+countries.size());

for(String country : countries) {

System.debug('Country: '+country);

}

}

}

Map

A map is a collection of key-value pairs where each unique
key maps to a single value. Keys and values can be any data type—primitive
types, collections, sObjects, user-defined types, and built-in Apex types.

To declare a map, use the Map keyword followed by the data
types of the key and the value within <> characters.

Map<String,
String> country_currencies = new Map<String, String>();

Map<ID,
Set<String>> m = new Map<ID, Set<String>>();

clear() :Removes all of the
key-value mappings from the map.

clone() :Makes a duplicate copy of
the map.

containsKey(Object) :Returnstrueif the map contains a
mapping for the specified key.

deepClone() :Makes a duplicate copy of
a map, including sObject records if this is a map with sObject record values.

equals(Map) :Compares this map with the
specified map and returnstrueif both maps are equal; otherwise, returnsfalse.

get(Object) :Returns the value to which
the specified key is mapped, ornullif the map contains no value for this key.

getSObjectType() :Returns the token of the
sObject type that makes up the map values.

hashCode() :Returns the hashcode
corresponding to this map.

isEmpty() :Returns true if the map
has zero key-value pairs.

keySet() :Returns a set that
contains all of the keys in the map.

put(Object, Object) :Associates the specified value with the
specified key in the map.

putAll(Map) :Copies all of the mappings
from the specified map to the original map.

putAll(sObject[]) :Adds the list of sObject
records to a map declared as Map<ID, sObject> or Map<String,
sObject>.

remove(Key) :Removes the mapping for
the specified key from the map, if present, and returns the corresponding value.

size() :Returns the number of
key-value pairs in the map.

values() :Returns a list that
contains all of the values in the map in arbitrary order.