Friday, July 26, 2019

SortedMap Vs TreeMap

SortedMap:-

public interface SortedMap<K,V> extends Map<K,V>
Type Parameters:
K - the type of keys maintained by this map
V - the type of mapped values

All Superinterfaces:
Map<K,V>

All Known Subinterfaces:
ConcurrentNavigableMap<K,V>, NavigableMap<K,V>

All Known Implementing Classes:
ConcurrentSkipListMap, TreeMap

SortedMap is a interface its extends Map interface. The SortedMap is ordered according to the natural ordering of its keys, or by a specified comparator. It is a part of collection framework and is present in java.util package.

SortedMap does not permit null keys but can have multiple null values.
If add null key then throw NullPointerException exception.

Example to test null key:

package com.shubh.example;

import java.util.SortedMap;
import java.util.TreeMap;

public class TreeMapExample {
 public static void main(String[] args) {
  SortedMap<String, String> mapDomains = new TreeMap<>();
  mapDomains.put("aa", "Hi Aa");
  mapDomains.put("bb", "Hi Bb");
  mapDomains.put(null, "Hi Cc");
  System.out.println(mapDomains);
 }
}
Output of test null key:-

Exception in thread "main" java.lang.NullPointerException
 at java.util.TreeMap.put(Unknown Source)
 at com.shubh.example.TreeMapExample.main(TreeMapExample.java:12)
Example to test null values:

package com.shubh.example;

import java.util.SortedMap;
import java.util.TreeMap;

public class TreeMapExample {
 public static void main(String[] args) {
  SortedMap<String, String> mapDomains = new TreeMap<>();
  mapDomains.put("aa", "Hi Aa");
  mapDomains.put("bb", null);
  mapDomains.put("cc", null);
  System.out.println(mapDomains);
 }
}
Output for test null values:

{aa=Hi Aa, bb=null, cc=null}
It is clear from the above examples.It does not permit null keys but we can add multiple null values.

TreeMap:- TreeMap is the implementation of NavigableMap interface which extends SortedMap interface that means we can say that TreeMap is the implementation of SortedMap interface.
Click here to see more in details about TreeMap.


Related Tutorials 

No comments:

Post a Comment