Java Collections - Part 2: Object Ordering

Gökhan Kanber
2 min readDec 28, 2020
Milky Way

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

  • List<String>: alphabetical
  • List<Date>: chronological
  • String and Date implements Comparable interface that provides natural ordering
Classes Implementing Comparable
Classes Implementing Comparable

Throws a ClassCastException

  • Collections.sort(list): objects that do not implement Comparable
  • Collections.sort(list, comparator): objects cannot be compared to one another using the comparator

Custom Comparable Types

The Comparable Interface

Custom Type

Program

Comparators

  • Sort objects in an order other than their natural ordering
  • That don’t implement Comparable

Comparator Interface

Implementation

Program

SortedSet

  • A Set that maintains its elements in ascending order
  • Provides additional ordering operations: range view, endpoints, comparator access
  • Range view: arbitrary range operations
  • Endpoints: first or last element
  • Comparator access: returns the Comparator

Range-view Operations

Endpoint Operations

Comparator Accessor

  • Copy a sorted set with the same ordering

SortedMap

  • A Map that maintains its mappings in ascending key order
  • Dictionaries, telephone directories
  • Provides additional ordering operations: range view, endpoints, comparator access
  • Range view: arbitrary range operations
  • Endpoints: first or last element
  • Comparator access: returns the Comparator

--

--