Introduction

In this article, we are going to describe the collection class and its commonly used methods in Java. The collection is a frame in Java. And the collection class found within the util package. Actually the Java collections framework is a set of classes and interfaces that are used to implement reusable collection data structures.

What is the Collection Framework?

collectio.JPG
The collections framework is a unified architecture for representing and manipulating collections, allowing them to be manipulated independently of the details of their representation. The collection framework provides better performance without complexity. It allows for interoperability among unrelated APIs, reduces the effort in designing and learning new APIs, and fosters software reuse. The framework is based on nine collection interfaces. It includes implementations of these interfaces, and algorithms to manipulate them.
The Collection framework mainly consists of the following:
Methods Explanation
Complete code
  1. import java.util.*;
  2. import java.util.Collections;
  3. public class Collection {
  4. public static void main(String[] args) {
  5. List list = Arrays.asList("Abhishek Amit Alok Anrudha omji".split(" "));
  6. List sublist = Arrays.asList("Arun");
  7. List searchList = Arrays.asList("Alok");
  8. System.out.println("Toatal Elements in list : " + list);
  9. Collections.copy(list, sublist);
  10. System.out.println("copied list : " + list);
  11. System.out.println("max value in list: " + Collections.max(list));
  12. System.out.println("min value in list : " + Collections.min(list));
  13. System.out.println("First Occurence of 'Alok: " + Collections.indexOfSubList(list, searchList));
  14. System.out.println("Last Occurence of Alok: " +
  15. Collections.lastIndexOfSubList(list, searchList));
  16. Collections.replaceAll(list, "Alok", "God");
  17. System.out.println("After replace Alok by God :" + list);
  18. Collections.reverse(list);
  19. System.out.println("Reverse order of List " + list);
  20. Collections.rotate(list, 3);
  21. System.out.println("Rotated by 3: " + list);
  22. System.out.println("Size of the list : " + list.size());
  23. Collections.swap(list, 0, list.size() - 1);
  24. System.out.println("After swapping List is: " + list);
  25. Collections.fill(list, "Mother");
  26. System.out.println("After filling all 'Mother' in list : " + list);
  27. List abhiList = Collections.nCopies(3, "Abhishek");
  28. System.out.println("List created by ncopy() " + abhiList);
  29. Enumeration e = Collections.enumeration(abhiList);
  30. Vector v = new Vector();
  31. while (e.hasMoreElements()) {
  32. v.addElement(e.nextElement());
  33. }
  34. ArrayList arrayList = Collections.list(v.elements());
  35. System.out.println("arrayList: " + arrayList);
  36. }
  37. }
Output
cmd.jpg