Updated version with CustomComparators and most of Linkedlist and arrays (where effective) replaced by ArrayLists.