Java Reference
In-Depth Information
public static void listEntries(Map<String,String> map) {
System.out.println("Entry Set:");
// Get the entry Set
Set<Map.Entry<String, String>>entries = map.entrySet();
entries.forEach((Map.Entry<String, String> entry) -> {
String key = entry.getKey();
String value = entry.getValue();
System.out.println("key=" + key + ", value=" + value);
});
}
}
Map: {Donna=(205)678-9823, Ken=(205)678-9823, John=(342)113-9878, Richard=(245)890-9045}
Key Set:
Donna
Ken
John
Richard
Values Collection:
(205)678-9823
(205)678-9823
(342)113-9878
(245)890-9045
Entry Set:
key=Donna, value=(205)678-9823
key=Ken, value=(205)678-9823
key=John, value=(342)113-9878
key=Richard, value=(245)890-9045
Sorted Maps
A sorted map stores entries in a map in an ordered way. It sorts the map entries on keys based on either natural sort
order or a custom sort order. The natural sort order is defined by the
Comparable
interface of the keys. If the keys do
not implement the
Comparable
interface, you must use a
Comparator
object to sort the entries. If the keys implement
the
Comparable
interface and you use a
Comparator
object, the
Comparator
object will be used to sort the keys.
An instance of the
SortedMap
interface represented a sorted map. The
SortedMap
interface inherits from the
Map
interface. A
SortedMap
is to a
Map
what a
SortedSet
is to a
Set
.
The
SortedMap
interface contains methods that let you take advantage of the sorted keys in the map. It has
methods that let you get the first and the last key or a submap based on a criteria, etc. Those methods are as follows:
Comparator<? super K> comparator()
: It returns the
Comparator
object used for custom
sorting of the keys in the
SortedMap
. If you have not used a
Comparator
object, it returns
null
and natural ordering will be used based on the implementation of the Comparable interface
for the keys.
•
K firstKey()
: It returns the key of the first entry in the
SortedMap
. If the
SortedMap
is empty,
it throws a
NoSuchElementException
.
•