Collections in Java

Arrays are used in java to store several objects. The issue with array is that it does not support dynamic allocation. It has a fixed length which is not changeable once it is declared. Moreover, array is a very simple linear structure and many applications require more flexible and complex structure such as linked list, trees, maps and sets. Java collections gave us opportunity to overcome this situation and are widely used by programmers in their programs.

What is a collection framework?

Caore Java library provides an interface called collection framework which give mandates the common behaviors of all classes and flexible data structures such as ArrayList, LinkedList, Vector, HashSet, Stack, Hashtable, and HashMap. Internally it uses the arrays for the storage and hide the complexity by managing the dynamic size. The data stored in the collection is encrypted and accessible via predefined methods. For example if an application stores the information of a student, collection stores the information of many students. Following are the key points that is been provided by collection interface.

Obtain high performance

Unified interface : allows different type of collections with common behavior and high level of interoperability

Extend or adopt the collections easily

Increase the software reuse ability

The Java Collection Framework package (java.util) contains:

A set of interfaces

Implementation classes

Algorithms (such as sorting and searching)

Important Default Implementation in Collections

Some of the most important implementations are stack, queue, dequeue, list, and tree. List interface has several implementation such as ArrayList and LinkedList classes. Following is the example which elaborates how to use List interface in your code.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

packageExamples;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

classListEx{

publicstaticvoidmain(String[]args){

// Create an instance

List lst=newArrayList();

// add() takes values or objects

lst.add("A");

lst.add("B");

lst.add("C");

System.out.println(lst);// [A, B, C]

// Get an iterator instance from List to iterate through all the elements of the List

Iterator iter=lst.iterator();

while(iter.hasNext()){// has more element in the list

// Retrieve the next element

Stringstr=(String)iter.next();

// print the element on console

System.out.println(str);

}

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

packageExamples;

import java.util.Arrays;

import java.util.List;

classListEx{

publicstaticvoidmain(String[]args){

List list=Arrays.asList(5,10,20,30,60,100);

for(Integerinteger:list){

System.out.println(integer);

}

}

}

In java 8 lambda expression are incorporated with collections to simplify the operations. The example below shows how to create a collection of type list which is parametrized with to indicate compiler that only Strings are allowed in this collection. Later it uses a foreach loop from java and pass a method reference to print the list elements on the screen.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

packageExamples;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

publicclassCollEx{

publicstaticvoidmain(String[]args){

// create an array list

List list=Arrays.asList("A","B","C");

// the alternative way to create array list is

List list2=newArrayList&lt;&gt;();

list2.add("A");

list2.add("B");

list2.add("C");

// print each element of an array list

list.forEach(System.out::println);

list2.forEach(System.out::println);

}

}

You may also sort the list using lambda expressions. The following example shows different ways to sort the list.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

packageExamples;

import java.util.Arrays;

import java.util.List;

classListEx{

publicstaticvoidmain(String[]args){

System.out.println("Sorting with natural order");

List list1=generateAList();

list1.sort(null);

list1.forEach(System.out::println);

System.out.println("Sorting with a lambda expression for the comparison");

Removing a list member using lambda expression. Following example shows how to remove A from the list.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

packageExamples;

import java.util.Arrays;

import java.util.List;

classListEx{

publicstaticvoidmain(String[]args){

System.out.println("Demonstration of removeIf");

List list1=generateAList();

// remove all items which contains an "A"

list1.removeIf(s-&gt;s.toLowerCase().contains("A"));

list1.forEach(s-&gt;System.out.println(s));

}

privatestaticList generateAList(){

returnArrays.asList("A","B","A","C");

}

}

Bulk Operation in Collection Interface

Java collections provides methods to perform bulk operations such as clear the whole list, merge two collections into one and remove all from the collection. One can use these shorthand operations using these operation provided by Collection interface. Following code elaborates the functionality of the following methods:

addAll: Adds all the elements of a Collection to another Collection

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

packageExamples;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collection;

import java.util.Collections;

import java.util.List;

publicclassMapEx{

publicstaticvoidmain(String[]args){

//Example 1 to use addAll collections method

//Create list1 and list2

ArrayList list1=newArrayList&lt;&gt;();

ArrayList list2=newArrayList&lt;&gt;();

//add some values in list1 and list2

list1.add(1);

list1.add(2);

list2.add(3.0);

list2.add(4.0);

//Create a 3rd collection list

Collection all=newArrayList();

//add / merge 1st and 2nd list

all.addAll(list1);

all.addAll(list2);

System.out.println(all.toString());

//Example 2 : using Arrays

List numList1=Arrays.asList(1,2,-1);

List numList2=Arrays.asList(4,5,6);

List allNum=newArrayList();

allNum.addAll(numList1);

allNum.addAll(numList2);

System.out.println(allNum);

//Example 3 :

Collections.addAll(all,"10","20","30");

System.out.println(all.toString());

}

}

containsAll: It returns true if target collection contains all elements in given collection

1

2

booleanb=all.containsAll(list1);

System.out.println(b);

removeAll: Removes all the elements from target collection that are also in specified collection

1

2

all.removeAll(list1);

System.out.println(all.toString());

retainAll: Retain only elements of target collection that are also in the specified collection