Collections – Sorted Map Interface

Hi all! Today i’m going to tell about Sorted Map Interface. We talked about Map Interface before this article. This interface extends Map interface. For example class that implements this interface is TreeMap.
Sorted Map doesn’t allow null keys and null values and it stores elements by sorting with keys.

Let’s take a look Sorted Map methods in shortly

subMap(K fromKey, K toKey) : It returns part of Map with keys range.
headMap(K toKey) : It returns part of Map whose keys are strictly less than toKey
tailMap(K fromKey) : It returns part of Map whose keys are greater than or equal fromKey
firstKey() : It returns fırst key currently in this Map.
lasKey() : It returns last key currently in this Map.
comparator() : It returns the Comparator used to order the keys in this Map.

Let’s check the example code.

import java.util.*;

public class Main {

    public static void main(String... args) {
        SortedMap<Integer, String> ageNameMap = new TreeMap<>();
        ageNameMap.put(26, "Ufuk");
        ageNameMap.put(24, "Halis");
        ageNameMap.put(28, "Alice");

        write(ageNameMap);
        System.out.println("---------------------------------------");
        System.out.println(ageNameMap.subMap(24,26));
        System.out.println(ageNameMap.headMap(27));
        System.out.println(ageNameMap.tailMap(25));
        System.out.println(ageNameMap.firstKey());
        System.out.println(ageNameMap.lastKey());
    }

    private static void write(Map map) {
        Set<Map.Entry> entries = map.entrySet();
        for (Map.Entry entry : entries) {
            System.out.println("Key : " + entry.getKey());
            System.out.println("Value : " + entry.getValue());
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s