Collections Class in Java
Collections class consists exclusively of static methods that operate on or return collections. It is present in java.util package.It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection, and a few other odds and ends.
The methods of this class all throw a NullPointerException if the collections or class objects provided to them are null.
The collection does not support modification,throws UnsupportedOperationException.
Fields in Collections Class
Following are the fields for java.util.Collections class −
static List EMPTY_LIST − This is the empty list (immutable
public static final List EMPTY_LIST;
static Map EMPTY_MAP − This is the empty map (immutable).
public static final Map EMPTY_MAP;
static Set EMPTY_SET − This is the empty set (immutable).
public static final Set EMPTY_SET;
Collection class methods
Now we will see the different methods provided by Collections class in java.
1). sort
Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
The specified list must be modifiable, but need not be resizable.
This implementation dumps the specified list into an array, sorts the array, and iterates over the list resetting each element from the corresponding position in the array. This avoids the n2 log(n) performance that would result from attempting to sort a linked list in place.
We can also pass in s Comparator, if we want some custom ordering.
List < String > langList = new ArrayList < >();
langList.add("Java");
langList.add("Php");
langList.add(".Net");
langList.add("Node");
langList.add("Python");
langList.add("Angular");
langList.add("Go");
langList.add("Scala");
langList.add("Groovy");
Collections.sort(langList);
2). addAll
public static <T> boolean addAll(Collection<? super T> c,
T... elements)
Adds all of the specified elements to the specified collection. Elements to be added may be specified individually or as an array. The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations.
List langList = new ArrayList();
Collections.addAll(langList, "Java", "Php", "Python","Node.js","Go","Groovy");
langList.forEach(System.out::println);
To know about addAll,please go throuth the article
3). binarySearch
Searches the specified list for the specified object using the binary search algorithm.
public static <T> int binarySearch(List<? extends Comparable<? super T>> list,
T key)
a). 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.
Collections.sort(langList);
System.out.println(Collections.binarySearch(langList, "Python"));
System.out.println(Collections.binarySearch(langList, "Php"));
System.out.println(Collections.binarySearch(langList, "Java"));
b). public static
Searches the specified list for the specified object using the binary search algorithm. The list must be sorted into ascending order according to the specified comparator (as by the sort(List, Comparator) 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.
4). shuffle
This method randomly permutes the specified list using a default source of randomness. All permutations occur with equal probability.
a). public static void shuffle(List list)
This implementation traverses the list backwards, from the last element up to the second, repeatedly swapping a randomly selected element into the "current position". Elements are randomly selected from the portion of the list that runs from the first element to the current position, inclusive.
Collections.shuffle(langList);
langList.forEach(System.out::println);
b).public static void shuffle(List list, Random rnd)
Randomly permute the specified list using the specified source of randomness.
5). reverse
This method reverses the order of the elements in the specified list.
public static void reverse(List list)
Collections.reverse(langList);
langList.forEach(System.out::println);
6).fill
This method replaces all of the elements of the specified list with the specified element.
public static
void fill(List list, T obj)
list - the list to be filled with the specified element.
obj - The element with which to fill the specified list.
Collections.fill(langList, "this is filled data");
langList.forEach(System.out::println);
7). min
This method returns the minimum element of the given collection, according to the natural ordering of its elements.
a). public static
All elements in the collection must implement the Comparable interface.
all elements in the collection must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the collection)
b). public static
This method returns the minimum element of the given collection, according to the order induced by the specified comparator.
8). max -
This method returns the maximum element of the given collection.
a). public static
This method returns the maximum element of the given collection, according to the natural ordering of its elements. All elements in the collection must implement the Comparable interface.
b). public static
Returns the maximum element of the given collection, according to the order induced by the specified comparator. All elements in the collection must be mutually comparable by the specified comparator (that is, comp.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the collection).
This method returns the maximum element of the given collection, according to the natural ordering of its elements.
9). rotate
This method rotates the elements in the specified list by the specified distance.
public static void rotate(List list,
int distance)
Collections.rotate(langList, 1);
langList.forEach(System.out::println);
10). replaceAll
This method Replaces all occurrences of one specified value in a list with another.
public static
boolean replaceAll(List list, T oldVal, T newVal);
true if list contained one or more elements e such that (oldVal==null ? e==null : oldVal.equals(e)).
11). unmodifiableCollection
This method Returns an unmodifiable view of the specified collection. This method allows modules to provide users with "read-only" access to internal collections.
public static
Collection unmodifiableCollection(Collection c)
The returned collection will be serializable if the specified collection is serializable.
12). unmodifiableSet
This method Returns an unmodifiable view of the specified set.
public static
Set unmodifiableSet(Set s)
This method allows modules to provide users with "read-only" access to internal sets.
Similarly we have methos
for SortedSet - unmodifiableSortedSet
for List - unmodifiableList
for Map - unmodifiableMap
for SortedMap - unmodifiableSortedMap etc
List < String > langList1 = Collections.unmodifiableList(langList);
langList1.forEach(System.out::println);
13). synchronizedCollection
This method returns a synchronized (thread-safe) collection backed by the specified collection.
Collection
synchronizedCollection = Collections.synchronizedCollection(langList);
similarly we have metjods for
List - Collections.synchronizedList(langList)
Set - Collections.synchronizedSet(set)
SortedSet - Collections.synchronizedSortedSet(sortedSet)
Map - Collections.synchronizedMap(map)
SortedMap - Collections.synchronizedSortedMap(map)
14). emptyIterator
This method returns an iterator that has no elements.
public static
Iterator emptyIterator()
More precisely,
hasNext always returns false.
next always throws NoSuchElementException.
remove always throws IllegalStateException.
Similarly we have ,
emptyListIterator
emptyEnumeration
emptySet
emptyList
emptyMap
15). singleton
This method returns an immutable set containing only the specified object. The returned set is serializable.
public static
Set singleton(T o)
Similarly we have
singletonList
singletonMap
16). enumeration
This method returns an enumeration over the specified collection. This provides interoperability with legacy APIs that require an enumeration as input.
public static
Enumeration enumeration(Collection c)
c - the collection for which an enumeration is to be returned.
17). list
This method returns an array list containing the elements returned by the specified enumeration in the order they are returned by the enumeration.
public static
ArrayList list(Enumeration e)
e - enumeration providing elements for the returned array list.
18). asLifoQueue
This method returns a view of a Deque as a Last-in-first-out (Lifo) Queue. Method add is mapped to push, remove is mapped to pop and so on. This view can be useful when you would like to use a method requiring a Queue but you need Lifo ordering.
public static
Queue asLifoQueue(Deque deque)
Each method invocation on the queue returned by this method results in exactly one method invocation on the backing deque, with one exception. The addAll method is implemented as a sequence of addFirst invocations on the backing deque.
Deque deque = new LinkedList();
deque.addFirst("Java");
deque.add("Php");
deque.add("C");
deque.addLast("Apple");
Queue queue = Collections.asLifoQueue(deque);
System.out.println(queue.poll());
System.out.println(queue.poll());
System.out.println(queue.poll());
19). swap
This method swaps the elements at the specified positions in the specified list.
public static void swap(List list,
int i,
int j)
list - The list in which to swap elements.
i - the index of one element to be swapped.
j - the index of the other element to be swapped.
20). copy
This method Copies all of the elements from one list into another.
public static
void copy(List dest, List src)
dest - The destination list.
src - The source list.
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.
List newlangList = new Arraylist<>();
Collections.copy(newlangList,langList);
newlangList.forEach(System.out::println);
Please refer docs for more details.
Post/Questions related to Collections Class in Java
How to get first element of collection in java?
How to initialize a collection in java?
How to compare two collections in java?
How do you create a new collection in Java?
Why do we use collections in java?
What is the difference between Java collection and Java collections?
In this article, we have seen Collections Class in Java with Examples. All source code in the article can be found in the GitHub repository.
0 Comments
Post a Comment