Java Collections - Part 5: Algorithms


This article is a part of the Java Programming Language article series.

  • Sorting
  • Shuffling
  • Routine Data Manipulation
  • Searching
  • Composition
  • Finding Extreme Values
  • Reorders a List in ascending order
  • Uses merge sort algorithm
  • The sort method:
    Collections.sort(list, comparator);
  • The opposite of sort
  • In all possible permutations with equal likelihood
  • Useful in implementing games of chance
  • The shuffle method
    Collections.shuffle(list, new Random());


  • Reverses the list order


  • Overwrites list elements with the specified value
  • Useful for reinitializing


  • Copies the elements
  • Destination and source arguments
  • Overwrites the contents
  • Destination list size must be equal or greater than source list size


  • Swaps list elements at the specified positions


  • Adds all the collection elements
  • Searches for a list element
  • The binarySearch method
  • Returns index value


  • Counts the number of times the specified element occurs in the specified collection


  • Determines two collections contain no elements in common
  • The min and the max methods


  • Interoperability between the core collection interfaces and the types that were used to represent collections in the early versions of the Java platform
    Vector, Hashtable, array, and Enumeration
  • Transform old collections to new collections and vice versa

API Design

  • Upward Compatibility
  • Backward Compatibility
  • Array to List
    Object[] objects;
  • Vector to List
  • Hashtable to Map
  • Enumeration to Collection
    Enumeration enumeration;
  • Collection to Array
    Collection collection;
    (String[]) collection.toArray(new String[0]);
  • Collection to Vector
    Collection collection;
    new Vector(collection);
  • Map to Hashtable
    Map map;
    new Hashtable(map);
  • Collection to Enumeration
    Collection collection;


  • Use interface types
  • Never use an implementation type
  • The best types to use on input are the most general
  • Collection and Map

Return Values

  • Return the most specific applicable collection interface rather than the most general

Legacy APIs

  • Define an adapter class that wraps the legacy collections objects



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store