Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

SortedMap Interface → SortedMap

SortedMap Interface

SortedMap

SortedMap Interface in Java Collections

SortedMap is an interface in the Java Collections Framework that extends the Map interface. It provides a way to store key-value pairs in a sorted order based on the natural ordering of its keys (if they implement Comparable) or a custom comparator provided during creation. This sorted nature allows for efficient retrieval and navigation based on the keys.

Characteristics of SortedMap

Ordering: Elements (key-value pairs) in a SortedMap are always maintained in a sorted order based on their keys. This is in contrast to HashMap, which is unordered. Natural Ordering or Comparator: By default, SortedMap implementations like TreeMap use the elements' natural ordering (if they implement Comparable). You can optionally provide a custom Comparator during creation to define your own sorting logic. Operations: SortedMap excels at operations that rely on the sorted nature of elements, such as finding the first or last key, retrieving elements within a specific range, or iterating through elements in sorted order. Implementations: The most common implementation of SortedMap is TreeMap, which uses a self-balancing binary search tree (like red-black tree) for efficient storage and retrieval of sorted elements.

Initialization & Declaration

Declaration
SortedMap declaration SortedMap mapName;
Params : SortedMap: This specifies the interface you're using. : Placeholders for the data types used for keys and values in the map. Keys must implement the Comparable interface for natural ordering, or a custom comparator can be used. mapName: The name for your reference variable.
Initialization While SortedMap is an interface, there's no direct way to create an instance of it. However, you can use concrete implementations like TreeMap that provide sorted key-value storage:
SortedMap Initialization// Using TreeMap (common implementation) SortedMap studentGrades = new TreeMap<>();
Explanation : This approach directly creates an empty TreeMap - a concrete implementation of SortedMap - with the specified key and value types.

Methods specific to SortedMap (not in Map):

firstKey(): Returns the first (smallest) key in the map according to the sorting order. ✦ lastKey(): Returns the last (largest) key in the map according to the sorting order. ✦ ceilingKey(key): Returns the least key in the map that is greater than or equal to the given key. ✦ floorKey(key): Returns the greatest key in the map that is less than or equal to the given key. ✦ subMap(fromKey, toKey): Returns a view of the portion of this map whose keys range from fromKey (inclusive) to toKey (exclusive). ✦ headMap(toKey): Returns a view of the portion of this map whose keys are less than toKey. ✦ tailMap(fromKey): Returns a view of the portion of this map whose keys are greater than or equal to fromKey.

Relationship between SortedMap and TreeMap:

✦ SortedMap is an interface, while TreeMap is a concrete implementation. ✦ Other implementations of SortedMap might exist, but TreeMap is the most widely used. ✦ When you need a sorted key-value collection, using TreeMap (which implements SortedMap) is the typical approach.

Examples for SortedMap (using TreeMap as the concrete implementation)

Maintaining a Phonebook Directory
SortedMap example in java collections - phonebook Directory import java.util.*; class Contact { String name; String phoneNumber; public Contact(String name, String phoneNumber) { this.name = name; this.phoneNumber = phoneNumber; } } public class Main { public static void main(String[] args) { SortedMap<String, Contact> phonebook = new TreeMap<>(); phonebook.put("Alice", new Contact("Alice Smith", "123-456-7890")); phonebook.put("Charlie", new Contact("Charlie Brown", "987-654-3210")); phonebook.put("Bob", new Contact("Bob Johnson", "555-123-4567")); for (String name : phonebook.keySet()) { System.out.println(name + ": " + phonebook.get(name).phoneNumber); } } }

Output

Alice: 123-456-7890 Bob: 555-123-4567 Charlie: 987-654-3210
Explanation : This example uses a TreeMap implementing SortedMap to store contacts in a phonebook. Since String implements Comparable, names are automatically sorted alphabetically, providing a convenient way to access contacts.
Sorted Inventory Management
SortedMap example in java collections - inventory management import java.util.*; class Product { int id; String name; double price; public Product(int id, String name, double price) { this.id = id; this.name = name; this.price = price; } } public class Main { public static void main(String[] args) { SortedMap<Integer, Product> inventory = new TreeMap<>(); inventory.put(102, new Product(102, "Shirt", 19.99)); inventory.put(101, new Product(101, "Cap", 12.50)); inventory.put(103, new Product(103, "Jacket", 59.95)); for (Product product : inventory.values()) { System.out.println(product.name + ": $" + product.price); } } }

Output

Cap: $12.5 Shirt: $19.99 Jacket: $59.95
Explanation : This example demonstrates storing product information in a sorted manner. Since keys are strings (sorted alphabetically by default), iterating over the values() of the TreeMap provides products in a sorted order by name.
Extracting Words from Text with Sorted Order
SortedMap example in java collections - extract words import java.util.*; public class Main { public static void main(String[] args) { String text = "The Sample sentence to extract words and to check the occurances"; SortedMap<String, Integer> wordCounts = new TreeMap<>(); for (String word : text.split(" ")) { word = word.toLowerCase(); // Case-insensitive counting int count = wordCounts.getOrDefault(word, 0); wordCounts.put(word, count + 1); } for (String word : wordCounts.keySet()) { System.out.println(word + ": " + wordCounts.get(word)); } } }

Output

and: 1 check: 1 extract: 1 occurances: 1 sample: 1 sentence: 1 the: 2 to: 2 words: 1
Explanation : This example processes text to extract words and count their occurrences. The TreeMap (implementing SortedMap) ensures that the extracted words are stored and displayed in alphabetical order.
Sorting Words by Length
SortedMap example in java collections - sorting words import java.util.*; public class Main { public static void main(String[] args) { SortedMap<String, Integer> nameLengths = new TreeMap<>(); nameLengths.put("sathish", 7); nameLengths.put("anand", 5); nameLengths.put("joseph", 6); for (String name : nameLengths.keySet()) { System.out.println(name + ": " + nameLengths.get(name) + " letters"); } } }

Output

anand: 5 letters joseph: 6 letters sathish: 7 letters
Explanation : This example uses TreeMap (implementing SortedMap) to store word lengths with words as keys. Since String implements Comparable, words are automatically sorted alphabetically.
Custom Class Keys with Sorted Order
SortedMap example in java collections - sorting keys import java.util.*; class Person { String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } } public class Main { public static void main(String[] args) { SortedMap<Person, String> peopleByAge = new TreeMap<>(new Comparator<Person>() { @Override public int compare(Person p1, Person p2) { return p1.age - p2.age; // Sort by age (ascending) } }); peopleByAge.put(new Person("Sathish", 30), "Details"); peopleByAge.put(new Person("Mohan", 25), "Details"); peopleByAge.put(new Person("Deva", 35), "Details"); for (Person person : peopleByAge.keySet()) { System.out.println(person.name + ": " + peopleByAge.get(person)); } } }

Output

Mohan: Details Sathish: Details Deva: Details
Explanation : This example defines a Person class with custom sorting based on age (ascending order) using a comparator during TreeMap initialization. This demonstrates how you can define your own sorting criteria for keys in a SortedMap implementation.

Tutorials