Skip to Content
Java Coding Problems
book

Java Coding Problems

by Anghel Leonard
September 2019
Intermediate to advanced
816 pages
18h 47m
English
Packt Publishing
Content preview from Java Coding Problems

Sorting by key via TreeMap and natural ordering

A quick solution to sorting a Map relies on TreeMap. By definition, the keys in TreeMap are sorted by their natural order. Moreover, TreeMap has a constructor of the TreeMap​(Map<? extends K,​? extends V> m) type:

public static <K, V> TreeMap<K, V> sortByKeyTreeMap(Map<K, V> map) {  return new TreeMap<>(map);}

And calling it will sort the map by key:

// {delicious=Apollo(3000g), // famous=Cantaloupe(1500g), refreshing=Jade Dew(3500g)}TreeMap<String, Melon> sortedMap = Maps.sortByKeyTreeMap(melons);
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java Coding Problems - Second Edition

Java Coding Problems - Second Edition

Anghel Leonard
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan
The Well-Grounded Java Developer, Second Edition

The Well-Grounded Java Developer, Second Edition

Benjamin Evans, Martijn Verburg, Jason Clark

Publisher Resources

ISBN: 9781789801415Supplemental Content