Skip to main content

Collections

java.util.Collections

It is part of the Collections Framework


tip

REFERENCE:~


About java.util.Collections


note
  • Unlike arrays, Collections do not have the [] operator.So, we use the get() method to access an element by its index.

  • There is one restriction, Collections cannot store primitive values at all (int, long, char, double, boolean and so on). We must use one of the wrapper classes (Integer, Long, Character, Double or another one) instead.

info

Collections provides useful methods to its different types of Collections like ArrayList, LinkedLiat, Vector, Stack.

  • SOME EXAMPLES:
  • It provides various Interfaces like List Interface which is implemented by classes such as ArrayList, LinkedList, Vector, Stack.
  • It provides Queue Interface which is implemented by classes such as PriorityQueue, Deque, ArrayDeque, etc.
  • It provides Deque Interface which is implemented by class ArrayDeque.
  • It provides Set Interface which is implemented by classes such as HashSet, TreeSet, LinkedHashSet, etc.
  • It Provides SortedSet Interface which is implemented by classes such as TreeSet
  • It Provides Map Interface which is implemented by classes such as HashMap, TreeMap, LinkedHashMap, etc.

https://www.geeksforgeeks.org/Collections-in-java-2/


Collections Methods

sort()

info

Sort in Ascending Order

Collections.sort() sorts the sequence (Collections which are in sequence such as ArrayList, LinkedList, Vector, Deque, Queue, Stack, etc.) in Ascending Order

ArrayList<Integer> al = new ArrayList<>();
while (sc.hasNext()) {
al.add(sc.nextInt());
} // al becomes [45, 5, 89, 65, 625, 165]

Collections.sort(al); // ArrayList "al" gets sorted to [5, 45, 65, 89, 165, 625]
System.out.println(al); // prints [5, 45, 65, 89, 165, 625]

Collections.sort(dataStructureName, reverseOrder())

info

Sort in Descending Order

Collections.sort(dataStructureName, reverseOrder()) sorts the sequence (Collections which are in sequence such as ArrayList, LinkedList, Vector, Deque, Queue, Stack, etc.) in Descending Order

ArrayList<Integer> al = new ArrayList<>();
while (sc.hasNext()) {
al.add(sc.nextInt());
} // al becomes [45, 5, 89, 65, 625, 165]

Collections.sort(al, Collections.reverseOrder()); // ArrayList "al" gets sorted to [625, 165, 89, 65, 45, 5]
System.out.println(al); // prints [625, 165, 89, 65, 45, 5]

addAll()

info

Collections.addAll(dataStructructureName, "element1", "element2", "element3", "element4") adds all of the specified elements to the specified collection whose variable name is dataStructructureName.

Here dataStructureName is the variable name of type of Collection such as ArrayList, LinkedList or other data structures which are part of the Java Collections.

ArrayList<String> al = new ArrayList<>();

Collections.addAll(al, "element1", "element2", "element3", "element4");
// It adds "element1", "element2", "element3", "element4" to the ArrayList 'al'
caution

Collections.addAll(dataStructructureName, "element1", "element2", "element3", "element4") also has two alternatives:

  • dataStructructureName.addAll(Arrays.asList("element1", "element2", "element3", "element4"))
  • datastructureName.addAll(List.of("element1", "element2", "element3", "element4"))

Best/Most Efficient is Collections.addAll(dataStructructureName, "element1", "element2", "element3", "element4")


Add an array to an ArrayList:

MUST KNOW: The array should be initiallised with Wrapper Classes such as Integer, String, Boolean, Char like:~ Integer[] arr... Otherwise addAll() would show an ERROR :~ The method addAll(Collection<? super T>, T...) in the type Collections is not applicable for the arguments (ArrayList<Integer>, int[])

ArrayList<Integer> al = new ArrayList<>();
Integer[] arr = { 4, 44, 4464, 46464, 464 };

al.add(56);
al.add(46);
al.add(136);
al.add(56313);
al.add(224);
al.add(5);

Collections.addAll(al, arr);
System.out.println(al);

reverse()

info

Collections.reverse(dataStructureName) reverses the order of the elements in the specified list.

Here dataStructureName is the variable name of type of Collection such as ArrayList, LinkedList or other data structures which are part of the Java Collections.

ArrayList<Integer> al = new ArrayList<>();
while (sc.hasNext()) { // taking the input until there is any input left
al.add(sc.nextInt()); // adding the inputs to ArrsyList "al"
}

Collections.reverse(al); // reverses the order of the elements of the ArrayList "al"

frequency()

info
  • Finds how many times a particular element comes in an ArrayList.
/* Input is:
4
5 54 65 56564 4 66 4
56 4 44 8 8 85 4 */
ArrayList<Integer> al1 = new ArrayList<>();
ArrayList<Integer> al2 = new ArrayList<>();

int n = sc.nextInt();
String x = sc.nextLine();

for (String el : sc.nextLine().split("\\s+")) { // Taking input for Arraylist by first taking "nextLine()" _ then 'split("\\s+")` ~ then converting to "Intger" by "Integer.parseInt(el)".
al1.add(Integer.parseInt(el));
}

for (String el : sc.nextLine().split("\\s+")) { // Taking input for Arraylist by first taking "nextLine()" _ then 'split("\\s+")` ~ then converting to "Intger" by "Integer.parseInt(el)".
al2.add(Integer.parseInt(el));
}

//Collections.frequency(al1, n) ⏩ It gives [ 2 ] as n=4 and 4 comes times in ArrayList "al1"
boolean check = Collections.frequency(al1, n) == (Collections.frequency(al2, n));
System.out.println(check); // prints true

fill()

info

Collections.fill(dataStructureName, x) fills the whole ArrayList or other such Data Structures with the given element "x"

// Input is [ hello my name is Sarthak ]
ArrayList<String> al = new ArrayList<>();
while (sc.hasNext()) {
al.add(sc.next());
}
System.out.println(al); // prints [hello, my, name, is, Sarthak]

Collections.fill(al, "Changed");
System.out.println(al); // prints [Changed, Changed, Changed, Changed, Changed]

min()

info
// Input is: [ 4 5 5 5 6 61 ]
ArrayList<Integer> al = new ArrayList<>();
while (sc.hasNext()) {
al.add(sc.nextInt());
}

System.out.println(Collections.min(al)); // prints: 4

Exception: This method throws following Exception👇

  • ClassCastException :~ If the collection contains elements that are not mutually comparable (for example, strings and integers).

  • NoSuchElementException :~ If the collection is empty


max()

info
// Input is: [ 4 5 5 5 6 61 ]
ArrayList<Integer> al = new ArrayList<>();
while (sc.hasNext()) {
al.add(sc.nextInt());
}

System.out.println(Collections.max(al)); // prints: 61

Exception: This method throws following Exception👇

  • ClassCastException :~ If the collection contains elements that are not mutually comparable (for example, strings and integers).

  • NoSuchElementException :~ If the collection is empty


rotate()


swap()


disjoint()


unmodifiableList()


binarySearch()

  • Large sorted data set (100,000 elements): Use binarySearch() but the sort() must have been applied first.
  • Small sorted data set (100 elements): Use indexOf()
  • Large unsorted data set (100,000 elements): Use binarySearch() but the sort() must have been applied first.
info

If the key is present:

/* Input is: [ 25    556   65  69 21 565 5565 45 ]
565 */
ArrayList<Integer> al = new ArrayList<>();
for (String el : sc.nextLine().split("\\s+")) {
al.add(Integer.parseInt(el));
}

int key = sc.nextInt();
System.out.println(key); // prints: 565
System.out.println(al); // [25, 556, 65, 69, 21, 565, 5565, 45]

Collections.sort(al);
System.out.println(Collections.binarySearch(al, key)); // prints: 6

If the key is NOT present:

If key is not present, the binarySearch() returns "(-(insertion point) - 1)".

ArrayList<Integer> al = new ArrayList<Integer>();
al.add(1);
al.add(2);
al.add(3);
al.add(10);
al.add(20);

// 10 is present at index 3.
int index = Collections.binarySearch(al, 10);
System.out.println(index);

/* 13 is not present. 13 would have been inserted
at position 4. as 13 is more than 10 and 10 is present at "Index = 3"; hence, 13 would have bveen insrted at the index after the index of 10, So 13 would be inserted at "Index = 4".
So the function returns (-4-1) which is " -5 ". */

index = Collections.binarySearch(al, 13);
System.out.println("Index is: " + index); // prints: -5

  • If input list is not sorted, the results are undefined.

  • The method throws ClassCastException if elements of list are not comparable using the specified comparator, or the search key is not comparable with the elements.

  • Searches the specified list for the specified object using the binary search algorithm. The list must be sorted into ascending order according to the natural ordering of its elements (as by the sort(List) method) prior to making this call. If it is not sorted, the results are undefined. If the list contains multiple elements equal to the specified object, there is no guarantee which one will be found.

  • This method runs in log(n) time for a "random access" list (which provides near-constant-time positional access). If the specified list does not implement the RandomAccess interface and is large, this method will do an iterator-based binary search that performs O(n) link traversals and O(log n) element comparisons.


  • Type Parameters:

    • the class of the objects in the list
  • Parameters:

    • list the list to be searched.
    • key the key to be searched for.
  • Returns:

    • the index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size() if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.
  • Throws:

    • ClassCastException - if the list contains elements that are not mutually comparable (for example, strings and integers), or the search key is not mutually comparable with the elements of the list.

Searching in Descending Order:

List<Integer> al = new ArrayList<Integer>();
al.add(100);
al.add(50);
al.add(30);
al.add(10);
al.add(2);

int key = 50;
// The last parameter specifies the comparator
// method used for sorting.
int index = Collections.binarySearch(al, key, Collections.reverseOrder());

System.out.println("Found at index " + index); // prints: " Found at index 1 "

copy()

info
  • Collections.copy(destList, srcList) copies all of the elements from srcList into destList.
  • After the operation, the index of each copied element in the destination list will be identical to its index in the source list. The destination list must be at least as long as the source list. If it is longer, the remaining elements in the destination list are unaffected.
ArrayList<Integer> li = new ArrayList<>(6);
li.add(663);
li.add(5);c
li.add(335);
System.out.println(li); // prints: [663, 5, 335]

ArrayList<Integer> al = new ArrayList<>();
al.add(45);
al.add(885);
al.add(556);
System.out.println(al); // prints: [45, 885, 556]

Collections.copy(al, li);
System.out.println(al); // prints: [663, 5, 335]

Exception: This method throws IndexOutOfBoundsException, if the destination list is too small to contain the entire source List.


indexOfSubList()

info
ArrayList<Integer> al1 = new ArrayList<>();
ArrayList<Integer> al2 = new ArrayList<>();

al1.add(56);
al1.add(46);
al1.add(136);
al1.add(56313);
al1.add(224);

al2.add(136);
al2.add(56313);
al2.add(224);

System.out.println(Collections.indexOfSubList(al1, al2)); // prints: 2
// The sublist "al2" begins from the "Index = 2"

lastIndexOfSubList()


... ...


... ...


Collections Interview Questions