Java TreeMap (με παραδείγματα)

Σε αυτό το σεμινάριο, θα μάθουμε για την κλάση Java TreeMap και τις λειτουργίες της με τη βοήθεια παραδειγμάτων.

Η TreeMapκλάση του πλαισίου συλλογών Java παρέχει την υλοποίηση της δομής δεδομένων δέντρων.

Υλοποιεί τη διασύνδεση NavigableMap.

Δημιουργία χάρτη χαρτών

Για να δημιουργήσουμε ένα TreeMap, πρέπει java.util.TreeMapπρώτα να εισαγάγουμε το πακέτο. Μόλις εισαγάγουμε το πακέτο, εδώ είναι πώς μπορούμε να δημιουργήσουμε ένα TreeMapJava.

 TreeMap numbers = new TreeMap(); 

Στον παραπάνω κώδικα, έχουμε δημιουργήσει TreeMapαριθμούς χωρίς όνομα. Σε αυτήν την περίπτωση, τα στοιχεία TreeMapταξινομούνται φυσικά (αύξουσα σειρά).

Ωστόσο, μπορούμε να προσαρμόσουμε την ταξινόμηση των στοιχείων χρησιμοποιώντας τη Comparatorδιεπαφή. Θα μάθουμε για αυτό αργότερα σε αυτό το σεμινάριο.

Εδώ,

  • Κλειδί - ένα μοναδικό αναγνωριστικό που χρησιμοποιείται για τη συσχέτιση κάθε στοιχείου (τιμή) σε έναν χάρτη
  • Τιμή - στοιχεία που σχετίζονται με κλειδιά σε έναν χάρτη

Μέθοδοι του TreeMap

Η TreeMapτάξη παρέχει διάφορες μεθόδους που μας επιτρέπουν να εκτελούμε λειτουργίες στο χάρτη.

Εισαγωγή στοιχείων στο TreeMap

  • put() - εισάγει την καθορισμένη αντιστοίχιση κλειδιού / τιμής (καταχώριση) στον χάρτη
  • putAll() - εισάγει όλες τις καταχωρήσεις από καθορισμένο χάρτη σε αυτόν τον χάρτη
  • putIfAbsent() - εισάγει την καθορισμένη αντιστοίχιση κλειδιού / τιμής στον χάρτη εάν το καθορισμένο κλειδί δεν υπάρχει στον χάρτη

Για παράδειγμα,

 import java.util.TreeMap; class Main ( public static void main(String() args) ( // Creating TreeMap of even numbers TreeMap evenNumbers = new TreeMap(); // Using put() evenNumbers.put("Two", 2); evenNumbers.put("Four", 4); // Using putIfAbsent() evenNumbers.putIfAbsent("Six", 6); System.out.println("TreeMap of even numbers: " + evenNumbers); //Creating TreeMap of numbers TreeMap numbers = new TreeMap(); numbers.put("One", 1); // Using putAll() numbers.putAll(evenNumbers); System.out.println("TreeMap of numbers: " + numbers); ) ) 

Παραγωγή

 TreeMap ζυγών αριθμών: (Four = 4, Six = 6, Two = 2) TreeMap αριθμών: (Four = 4, One = 1, Six = 6, Two = 2) 

Πρόσβαση στα στοιχεία TreeMap

1. Χρήση του entrySet (), keySet () και των τιμών ()

  • entrySet() - επιστρέφει ένα σύνολο όλων των αντιστοίχισης κλειδιών / τιμών (εισαγωγή) ενός χάρτη πορείας
  • keySet() - επιστρέφει ένα σύνολο όλων των κλειδιών ενός χάρτου δέντρων
  • values() - επιστρέφει ένα σύνολο όλων των χαρτών ενός δέντρου

Για παράδειγμα,

 import java.util.TreeMap; class Main ( public static void main(String() args) ( TreeMap numbers = new TreeMap(); numbers.put("One", 1); numbers.put("Two", 2); numbers.put("Three", 3); System.out.println("TreeMap: " + numbers); // Using entrySet() System.out.println("Key/Value mappings: " + numbers.entrySet()); // Using keySet() System.out.println("Keys: " + numbers.keySet()); // Using values() System.out.println("Values: " + numbers.values()); ) ) 

Παραγωγή

 TreeMap: (One = 1, Three = 3, Two = 2) Αντιστοίχιση κλειδιού / τιμής: (One = 1, Three = 3, Two = 2) Keys: (One, Three, Two) Τιμές: (1, 3, 2 ) 

2. Χρησιμοποιώντας get () και getOrDefault ()

  • get()- Επιστρέφει την τιμή που σχετίζεται με το καθορισμένο κλειδί. Επιστρέφει null εάν το κλειδί δεν βρεθεί.
  • getOrDefault()- Επιστρέφει την τιμή που σχετίζεται με το καθορισμένο κλειδί. Επιστρέφει την καθορισμένη προεπιλεγμένη τιμή εάν το κλειδί δεν βρεθεί.

Για παράδειγμα,

 import java.util.TreeMap; class Main ( public static void main(String() args) ( TreeMap numbers = new TreeMap(); numbers.put("One", 1); numbers.put("Two", 2); numbers.put("Three", 3); System.out.println("TreeMap: " + numbers); // Using get() int value1 = numbers.get("Three"); System.out.println("Using get(): " + value1); // Using getOrDefault() int value2 = numbers.getOrDefault("Five", 5); System.out.println("Using getOrDefault(): " + value2); ) ) 

Παραγωγή

 TreeMap: (One = 1, Three = 3, Two = 2) Using get (): 3 Using getOrDefault (): 5 

Εδώ, η getOrDefault()μέθοδος δεν βρίσκει το κλειδί Five. Ως εκ τούτου επιστρέφει την καθορισμένη προεπιλεγμένη τιμή 5.

Κατάργηση στοιχείων TeeMap

  • remove(key) - επιστρέφει και καταργεί την καταχώριση που σχετίζεται με το καθορισμένο κλειδί από το TreeMap
  • remove(key, value) - αφαιρεί την καταχώριση από το χάρτη μόνο εάν το καθορισμένο κλειδί συσχετίζεται με την καθορισμένη τιμή και επιστρέφει μια δυαδική τιμή

Για παράδειγμα,

 import java.util.TreeMap; class Main ( public static void main(String() args) ( TreeMap numbers = new TreeMap(); numbers.put("One", 1); numbers.put("Two", 2); numbers.put("Three", 3); System.out.println("TreeMap: " + numbers); // remove method with single parameter int value = numbers.remove("Two"); System.out.println("Removed value: " + value); // remove method with two parameters boolean result = numbers.remove("Three", 3); System.out.println("Is the entry (Three=3) removed? " + result); System.out.println("Updated TreeMap: " + numbers); ) ) 

Παραγωγή

TreeMap: (One = 1, Three = 3, Two = 2) Αφαιρούμενη τιμή = 2 Καταργείται η καταχώριση (Three = 3); True Update TreeMap: (Ένα = 1)

Αντικαταστήστε τα στοιχεία TreeMap

  • replace(key, value) - αντικαθιστά την τιμή που έχει αντιστοιχιστεί από το καθορισμένο κλειδί με τη νέα τιμή
  • replace(key, old, new) - αντικαθιστά την παλιά τιμή με τη νέα τιμή μόνο εάν η παλιά τιμή έχει ήδη συσχετιστεί με το καθορισμένο κλειδί
  • replaceAll(function) - αντικαθιστά κάθε τιμή του χάρτη με το αποτέλεσμα της καθορισμένης συνάρτησης

Για παράδειγμα,

 import java.util.TreeMap; class Main ( public static void main(String() args) ( TreeMap numbers = new TreeMap(); numbers.put("First", 1); numbers.put("Second", 2); numbers.put("Third", 3); System.out.println("Original TreeMap: " + numbers); // Using replace() numbers.replace("Second", 22); numbers.replace("Third", 3, 33); System.out.println("TreeMap using replace: " + numbers); // Using replaceAll() numbers.replaceAll((key, oldValue) -> oldValue + 2); System.out.println("TreeMap using replaceAll: " + numbers); ) ) 

Παραγωγή

 Original TreeMap: (First=1, Second=2, Third=3) TreeMap using replace(): (First=1, Second=22, Third=33) TreeMap using replaceAll(): (First=3, Second=24, Third=35) 

In the above program notice the statement

 numbers.replaceAll((key, oldValue) -> oldValue + 2); 

Here, we have passed a lambda expression as an argument.

The replaceAll() method accesses all the entries of the map. It then replaces all the elements with the new values (returned from the lambda expression).

Methods for Navigation

Since the TreeMap class implements NavigableMap, it provides various methods to navigate over the elements of the treemap.

1. First and Last Methods

  • firstKey() - returns the first key of the map
  • firstEntry() - returns the key/value mapping of the first key of the map
  • lastKey() - returns the last key of the map
  • lastEntry() - returns the key/value mapping of the last key of the map

For example,

 import java.util.TreeMap; class Main ( public static void main(String() args) ( TreeMap numbers = new TreeMap(); numbers.put("First", 1); numbers.put("Second", 2); numbers.put("Third", 3); System.out.println("TreeMap: " + numbers); // Using the firstKey() method String firstKey = numbers.firstKey(); System.out.println("First Key: " + firstKey); // Using the lastKey() method String lastKey = numbers.lastKey(); System.out.println("Last Key: " + lastKey); // Using firstEntry() method System.out.println("First Entry: " + numbers.firstEntry()); // Using the lastEntry() method System.out.println("Last Entry: " + numbers.lastEntry()); ) ) 

Output

 TreeMap: (First=1, Second=2, Third=3) First Key: First Last Key: Third First Entry: First=1 Last Entry: Third=3 

2. Ceiling, Floor, Higher and Lower Methods

  • higherKey() - Returns the lowest key among those keys that are greater than the specified key.
  • higherEntry() - Returns an entry associated with a key that is lowest among all those keys greater than the specified key.
  • lowerKey() - Returns the greatest key among all those keys that are less than the specified key.
  • lowerEntry() - Returns an entry associated with a key that is greatest among all those keys that are less than the specified key.
  • ceilingKey() - Returns the lowest key among those keys that are greater than the specified key. If the key passed as an argument is present in the map, it returns that key.
  • ceilingEntry() - Returns an entry associated with a key that is lowest among those keys that are greater than the specified key. It an entry associated with the key passed an argument is present in the map, it returns the entry associated with that key.
  • floorKey() - Returns the greatest key among those keys that are less than the specified key. If the key passed as an argument is present, it returns that key.
  • floorEntry() - Returns an entry associated with a key that is greatest among those keys that are less than the specified key. If the key passed as argument is present, it returns that key.

For example,

 import java.util.TreeMap; class Main ( public static void main(String() args) ( TreeMap numbers = new TreeMap(); numbers.put("First", 1); numbers.put("Second", 5); numbers.put("Third", 4); numbers.put("Fourth", 6); System.out.println("TreeMap: " + numbers); // Using higher() System.out.println("Using higherKey(): " + numbers.higherKey("Fourth")); System.out.println("Using higherEntry(): " + numbers.higherEntry("Fourth")); // Using lower() System.out.println("Using lowerKey(): " + numbers.lowerKey("Fourth")); System.out.println("Using lowerEntry(): " + numbers.lowerEntry("Fourth")); // Using ceiling() System.out.println("Using ceilingKey(): " + numbers.ceilingKey("Fourth")); System.out.println("Using ceilingEntry(): " + numbers.ceilingEntry("Fourth")); // Using floor() System.out.println("Using floorKey(): " + numbers.floorKey("Fourth")); System.out.println("Using floorEntry(): " + numbers.floorEntry("Fourth")); ) ) 

Output

 TreeMap: (First=1, Fourth=6, Second=5, Third=4) Using higherKey(): Second Using higherEntry(): Second=5 Using lowerKey(): First Using lowerEntry(): First=1 Using ceilingKey(): Fourth Using ceilingEntry(): Fourth=6 Using floorkey(): Fourth Using floorEntry(): Fourth=6 

3. pollFirstEntry() and pollLastEntry() Methods

  • pollFirstEntry() - returns and removes the entry associated with the first key of the map
  • pollLastEntry() - returns and removes the entry associated with the last key of the map

For example,

 import java.util.TreeMap; class Main ( public static void main(String() args) ( TreeMap numbers = new TreeMap(); numbers.put("First", 1); numbers.put("Second", 2); numbers.put("Third", 3); System.out.println("TreeMap: " + numbers); //Using the pollFirstEntry() method System.out.println("Using pollFirstEntry(): " + numbers.pollFirstEntry()); // Using the pollLastEntry() method System.out.println("Using pollLastEntry(): " + numbers.pollLastEntry()); System.out.println("Updated TreeMap: " + numbers); ) ) 

Output

 TreeMap: (First=1, Second=2, Third=3) Using pollFirstEntry(): First=1 Using pollLastEntry(): Third=3 Updated TreeMap: (Second=2) 

4. headMap(), tailMap() and subMap() Methods

headMap(key, booleanValue)

The headMap() method returns all the key/value pairs of a treemap before the specified key (which is passed as an argument).

The booleanValue parameter is optional. Its default value is false.

If true is passed as a booleanValue, the method also includes the key/value pair of the key which is passed as an argument.

For example,

 import java.util.TreeMap; class Main ( public static void main(String() args) ( TreeMap numbers = new TreeMap(); numbers.put("First", 1); numbers.put("Second", 2); numbers.put("Third", 3); numbers.put("Fourth", 4); System.out.println("TreeMap: " + numbers); System.out.println("Using headMap() Method:"); // Using headMap() with default booleanValue System.out.println("Without boolean value: " + numbers.headMap("Fourth")); // Using headMap() with specified booleanValue System.out.println("With boolean value: " + numbers.headMap("Fourth", true)); ) ) 

Output

 TreeMap: (First=1, Fourth=4, Second=2, Third=3) Using headMap() Method: Without boolean value: (First=1) With boolean value: (First=1, Fourth=4) 

tailMap(key, booleanValue)

The tailMap() method returns all the key/value pairs of a treemap starting from the specified key (which is passed as an argument).

The booleanValue is an optional parameter. Its default value is true.

If false is passed as a booleanValue, the method doesn't include the key/value pair of the specified key.

For example,

 import java.util.TreeMap; class Main ( public static void main(String() args) ( TreeMap numbers = new TreeMap(); numbers.put("First", 1); numbers.put("Second", 2); numbers.put("Third", 3); numbers.put("Fourth", 4); System.out.println("TreeMap: " + numbers); System.out.println("Using tailMap() Method:"); // Using tailMap() with default booleanValue System.out.println("Without boolean value: " + numbers.tailMap("Second")); // Using tailMap() with specified booleanValue System.out.println("With boolean value: " + numbers.tailMap("Second", false)); ) ) 

Output

 TreeMap: (First=1, Fourth=4, Second=2, Third=3) Using tailMap() Method: Without boolean value: (Second=2, Third=3) With boolean value: (Third=3) 

subMap(k1, bV1, k2, bV2)

The subMap() method returns all the entries associated with keys between k1 and k2 including the entry of k1.

The bV1 and bV2 are optional boolean parameters. The default value of bV1 is true and the default value of bV2 is false.

If false is passed as bV1, the method returns all the entries associated with keys between k1 and k2 without including the entry of k1.

If true is passed as bV2, the method returns all the entries associated with keys between k1 and k2 including the entry of k2.

For example,

 import java.util.TreeMap; class Main ( public static void main(String() args) ( TreeMap numbers = new TreeMap(); numbers.put("First", 1); numbers.put("Second", 2); numbers.put("Third", 3); numbers.put("Fourth", 4); System.out.println("TreeMap: " + numbers); System.out.println("Using subMap() Method:"); // Using subMap() with default booleanValue System.out.println("Without boolean value: " + numbers.subMap("Fourth", "Third")); // Using subMap() with specified booleanValue System.out.println("With boolean value: " + numbers.subMap("Fourth", false, "Third", true)); ) ) 

Output

 TreeMap: (First=1, Fourth=2, Second=2, Third=3) Using subMap() Method: Without boolean value: (Fourth=4, Second=2) With boolean value: (Second=2, Third=3) 

Other Methods of TreeMap

Method Description
clone() Creates a copy of the TreeMap
containsKey() Searches the TreeMap for the specified key and returns a boolean result
containsValue() Searches the TreeMap for the specified value and returns a boolean result
size() Returns the size of the TreeMap
clear() Removes all the entries from the TreeMap

TreeMap Comparator

In all the examples above, treemap elements are sorted naturally (in ascending order). However, we can also customize the ordering of keys.

For this, we need to create our own comparator class based on which keys in a treemap are sorted. For example,

 import java.util.TreeMap; import java.util.Comparator; class Main ( public static void main(String() args) ( // Creating a treemap with a customized comparator TreeMap numbers = new TreeMap(new CustomComparator()); numbers.put("First", 1); numbers.put("Second", 2); numbers.put("Third", 3); numbers.put("Fourth", 4); System.out.println("TreeMap: " + numbers); ) // Creating a comparator class public static class CustomComparator implements Comparator ( @Override public int compare(String number1, String number2) ( int value = number1.compareTo(number2); // elements are sorted in reverse order if (value> 0) ( return -1; ) else if (value < 0) ( return 1; ) else ( return 0; ) ) ) ) 

Output

 TreeMap: (Third=3, Second=2, Fourth=4, First=1) 

Στο παραπάνω παράδειγμα, έχουμε δημιουργήσει έναν χάρτη πορείας που περνά την κλάση CustomComparator ως επιχείρημα.

Η κλάση CustomComparator εφαρμόζει τη Comparatorδιεπαφή.

Στη συνέχεια παρακάμπτουμε τη compare()μέθοδο ταξινόμησης στοιχείων με αντίστροφη σειρά.

Για να μάθετε περισσότερα, επισκεφθείτε το Java Comparator (επίσημη τεκμηρίωση Java).

ενδιαφέροντα άρθρα...