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.
package Examples; import java.util.ArrayList; import java.util.Iterator; import java.util.List; class ListEx { public static void main(String[] args) { // Create an instance List lst = new ArrayList(); // 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 String str = (String)iter.next(); // print the element on console System.out.println(str); } } }
package Examples; import java.util.Arrays; import java.util.List; class ListEx { public static void main(String[] args) { List list = Arrays.asList(5,10,20,30,60,100); for (Integer integer : 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.
package Examples; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CollEx { public static void main(String[] args) { // create an array list List list = Arrays.asList("A", "B","C"); // the alternative way to create array list is List list2 = new ArrayList<>(); 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.
package Examples; import java.util.Arrays; import java.util.List; class ListEx { public static void main(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"); List list2 = generateAList(); list2.sort((s1, s2) -> s1.compareToIgnoreCase(s2)); // sort ignoring case list2.forEach(System.out::println); System.out.println("Sorting with a method references"); List list3 = generateAList(); list3.sort(String::compareToIgnoreCase); list3.forEach(System.out::println); } private static List generateAList() { return Arrays.asList("D", "B", "A", "C"); } }
Removing a list member using lambda expression. Following example shows how to remove A from the list.
package Examples; import java.util.Arrays; import java.util.List; class ListEx { public static void main(String[] args) { System.out.println("Demonstration of removeIf"); List list1 = generateAList(); // remove all items which contains an "A" list1.removeIf(s-> s.toLowerCase().contains("A")); list1.forEach(s->System.out.println(s)); } private static List generateAList() { return Arrays.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
package Examples; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; public class MapEx { public static void main(String[] args) { //Example 1 to use addAll collections method //Create list1 and list2 ArrayList list1 = new ArrayList<>(); ArrayList list2 = new ArrayList<>(); //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 = new ArrayList(); //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 = new ArrayList(); 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
boolean b = all.containsAll(list1); System.out.println(b);
removeAll: Removes all the elements from target collection that are also in specified collection
all.removeAll(list1); System.out.println(all.toString());
retainAll: Retain only elements of target collection that are also in the specified collection
all.retainAll(list2); System.out.println(all.toString());
clear: Clears/removes all elements from a collection
all.clear(); System.out.println(all.toString());
More Useful Methods in Collections Class
Sort Method
Collections.sort(list1); System.out.println(list1.toString());
Reverse Method
Collections.reverse(list1); System.out.println(list1.toString());
Copy Method
Copy all elements from source to target collection.
ArrayList a = new ArrayList(); a.add(5); a.add(10); ArrayList b = new ArrayList(a.size()); Collections.copy(b,a );
Shuffle Method
Collections.shuffle(list1);
Swap Method
Swap element 0 and 1 from the given list.
Collections.swap(list1,0,1 );
No Responses