We’ve seen the many benefits of the collection framework and how they provide ready-to-use implementations so we don’t have to create them ourselves. What should we do when we need to sort a collection or get some statistic like the max or minimum element in the collection? The collection framework provides the Collections
class that has many static
methods that perform these types of calculations for us.
There are many methods provided in the Collections
class and we’ll cover a subset of those below:
binarySearch()
: Performs binary search over aList
to find the specified object and returns the index if found. This method is overloaded to also accept aComparator
in order to define a custom sorting algorithm.max()
: Finds and returns the maximum element in theCollection
. This method is overloaded to also accept aComparator
in order to define a custom sorting algorithm.min()
: Finds and returns the minimum element in theCollection
. This method is overloaded to also accept aComparator
in order to define a custom sorting algorithm.reverse()
: Reverses the order of elements in theList
passed in as an argument.sort()
: Sorts theList
passed in as an argument. This method is overloaded to also accept aComparator
in order to define a custom sorting algorithm.
These utility methods on the collection framework make performing complex calculations or gaining insight into the collection of data we have easy and efficient.
Let’s practice using some Collections
methods.
Instructions
Look at the code editor and run the program to see Collections
algorithms used.