Interface SortedMap
Type Parameters: K — the type of keys maintained by this map V — the type of mapped values All Superinterfaces: Map All Known Subinterfaces: ConcurrentNavigableMap , NavigableMap All Known Implementing Classes: ConcurrentSkipListMap , TreeMap
A Map that further provides a total ordering on its keys. The map is ordered according to the natural ordering of its keys, or by a Comparator typically provided at sorted map creation time. This order is reflected when iterating over the sorted map’s collection views (returned by the entrySet , keySet and values methods). Several additional operations are provided to take advantage of the ordering. (This interface is the map analogue of SortedSet .)
All keys inserted into a sorted map must implement the Comparable interface (or be accepted by the specified comparator). Furthermore, all such keys must be mutually comparable: k1.compareTo(k2) (or comparator.compare(k1, k2) ) must not throw a ClassCastException for any keys k1 and k2 in the sorted map. Attempts to violate this restriction will cause the offending method or constructor invocation to throw a ClassCastException .
Note that the ordering maintained by a sorted map (whether or not an explicit comparator is provided) must be consistent with equals if the sorted map is to correctly implement the Map interface. (See the Comparable interface or Comparator interface for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare ) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a tree map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.
- A void (no arguments) constructor, which creates an empty sorted map sorted according to the natural ordering of its keys.
- A constructor with a single argument of type Comparator , which creates an empty sorted map sorted according to the specified comparator.
- A constructor with a single argument of type Map , which creates a new map with the same key-value mappings as its argument, sorted according to the keys’ natural ordering.
- A constructor with a single argument of type SortedMap , which creates a new sorted map with the same key-value mappings and the same ordering as the input sorted map.
Note: several methods return submaps with restricted key ranges. Such ranges are half-open, that is, they include their low endpoint but not their high endpoint (where applicable). If you need a closed range (which includes both endpoints), and the key type allows for calculation of the successor of a given key, merely request the subrange from lowEndpoint to successor(highEndpoint) . For example, suppose that m is a map whose keys are strings. The following idiom obtains a view containing all of the key-value mappings in m whose keys are between low and high , inclusive:
SortedMap sub = m.subMap(low, high+"\0");
A similar technique can be used to generate an open range (which contains neither endpoint). The following idiom obtains a view containing all of the key-value mappings in m whose keys are between low and high , exclusive:
SortedMap sub = m.subMap(low+"\0", high);
This interface is a member of the Java Collections Framework.
Create an Ordered Map in Java
- Sort the Map Using the TreeMap Class in Java
- Create a Map Ordering Using Java 8 Functions
A map is a data structure in Java that stores key and value pairs. The map is an interface present in the Collection hierarchy. These keys are unique so, no duplicate keys are allowed; however, the variables mapped to the key can have duplicate values. Classes like HashMap , LinkedHashMap , and TreeMap implement the Map interface.
Sort the Map Using the TreeMap Class in Java
Below, the program demonstrates the map ordering in the Java program.
import java.util.TreeMap; public class Main public static void main(String[] args) TreeMapString, Integer> map = new TreeMapString, Integer>(); map.put("Third", 1); map.put("First", 2); map.put("Second", 3); for (String key: map.keySet()) System.out.println(key + " ,ID = "+ map.get(key) ); > > >
The TreeMap class sorts the map values in ascending order. It also implements the SortedMap interface internally, so a map instance is created using a new keyword.
The datatype inside the treemap is specified at the time of instantiation. The Map key is of the String type, and its value is of the Integer type.
The put function inserts the key-value pairs in the treemap. Now, a for-each loop gets defined to iterate over the map. In Java, direct iteration over the map is not possible. So, the keys of the map are initially converted to a Set instance.
The map.keySet function returns the Set of keys present in the map. This function is in the TreeMap class and returns the ordered view of the keys present. The get function gets the value corresponding to the key.
Below is the output in ascending order.
First ,ID = 2 Second ,ID = 3 Third ,ID = 1
Create a Map Ordering Using Java 8 Functions
Java 8 provides support for functional programming that allows users to work over the chain of functions.
Streams is an interface in the java.util package that provides an ease to work over the sequential operations in a single statement. The Streams function works in the pipeline where an emitter emits data; it gets filtered, processed, transformed, and much more, depending on the users’ needs.
package F09; import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.util.AbstractMap.SimpleEntry; public class MapOrdering public static void main(String[] args) MapString, String> mapSortedByKey = Stream.of( new SimpleEntry<>("key3", "value1"), new SimpleEntry<>("key1", "value2"), new SimpleEntry<>("key2", "value3")) .sorted(Map.Entry.comparingByKey()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldVal, newValue) -> oldVal, LinkedHashMap::new)); System.out.println(); System.out.print("Ordered List: "); for (String s1 : mapSortedByKey.keySet()) System.out.print(" " + s1); > > >
The Stream interface provides various functions and gets its implementation in different classes to work over them. Here, the stream of key-value pairs is formed using the new SimpleEntry class. The values are inserted in the of function to form a stream.
In the chain series, the sorted function gets called. The function takes a Comparator instance to arrange the keys in a sequence depending on the order defined. The function comparingByKey returns the comparator that compares the key in natural ascending order.
The sorted function finally returns a stream of values arranged in ascending order. The collect function of the Stream class collects the given map values in a new LinkedHashMap instance. The class preserves the insertion order of the sequence provided. The function takes the Collector instance as a parameter.
The first parameter is a supplier toMap function that creates a new container. The second parameter is BiConsumer that accumulates the value, and the last parameter is BiConsumer that acts as a combiner that merges the results. So, the LinkedHashMap::new command combines the result and returns the instance formed.
The mapSortedByKey instance now holds the sequential map elements that get iterated using the for-each loop above. The resultant map keys are printed in the standard output below.
Ordered List: key1 key2 key3
Rashmi is a professional Software Developer with hands on over varied tech stack. She has been working on Java, Springboot, Microservices, Typescript, MySQL, Graphql and more. She loves to spread knowledge via her writings. She is keen taking up new things and adopt in her career.
Related Article — Java Map
Related Article — Java Sort
Copyright © 2023. All right reserved
Interface SortedMap
Type Parameters: K — the type of keys maintained by this map V — the type of mapped values All Superinterfaces: Map All Known Subinterfaces: ConcurrentNavigableMap , NavigableMap All Known Implementing Classes: ConcurrentSkipListMap , TreeMap
A Map that further provides a total ordering on its keys. The map is ordered according to the natural ordering of its keys, or by a Comparator typically provided at sorted map creation time. This order is reflected when iterating over the sorted map’s collection views (returned by the entrySet , keySet and values methods). Several additional operations are provided to take advantage of the ordering. (This interface is the map analogue of SortedSet .)
All keys inserted into a sorted map must implement the Comparable interface (or be accepted by the specified comparator). Furthermore, all such keys must be mutually comparable: k1.compareTo(k2) (or comparator.compare(k1, k2) ) must not throw a ClassCastException for any keys k1 and k2 in the sorted map. Attempts to violate this restriction will cause the offending method or constructor invocation to throw a ClassCastException .
Note that the ordering maintained by a sorted map (whether or not an explicit comparator is provided) must be consistent with equals if the sorted map is to correctly implement the Map interface. (See the Comparable interface or Comparator interface for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare ) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a tree map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.
- A void (no arguments) constructor, which creates an empty sorted map sorted according to the natural ordering of its keys.
- A constructor with a single argument of type Comparator , which creates an empty sorted map sorted according to the specified comparator.
- A constructor with a single argument of type Map , which creates a new map with the same key-value mappings as its argument, sorted according to the keys’ natural ordering.
- A constructor with a single argument of type SortedMap , which creates a new sorted map with the same key-value mappings and the same ordering as the input sorted map.
Note: several methods return submaps with restricted key ranges. Such ranges are half-open, that is, they include their low endpoint but not their high endpoint (where applicable). If you need a closed range (which includes both endpoints), and the key type allows for calculation of the successor of a given key, merely request the subrange from lowEndpoint to successor(highEndpoint) . For example, suppose that m is a map whose keys are strings. The following idiom obtains a view containing all of the key-value mappings in m whose keys are between low and high , inclusive:
SortedMap sub = m.subMap(low, high+"\0");
A similar technique can be used to generate an open range (which contains neither endpoint). The following idiom obtains a view containing all of the key-value mappings in m whose keys are between low and high , exclusive:
SortedMap sub = m.subMap(low+"\0", high);
This interface is a member of the Java Collections Framework.