zoukankan      html  css  js  c++  java
  • Java Sorted Map Example

     

    In this example we shall show you how to make use of Java Sorted Map. A SortedMap is a Map that sort its entries in ascending order according to the keys’ natural ordering, or according to a Comparator provided at the time of the SortedMap creation. All keys inserted into a SortedMap must implement the Comparable interface (or be accepted by the specified Comparator). Furthermore, all such elements must be mutually comparable (i.e, Mutually Comparable simply means that two objects accept each other as the argument to their compareTo method), If you try to sort keys which do not implement Comparable or not has a specific Comparator, a ClassCastException will be thrown.

    Tip 1

    java.lang.Comparable: int compareTo(Object o):

    This method compares this object with o object. Returned int value has the following meanings.

    • positive – this object is greater than o
    • zero – this object equals to o
    • negative – this object is less than o

    Also, we can use our own Comparator. If you need to know more about the Comparable andComparator, Take a look on Java Comparable and Comparator Example to sort Objects by Byron Kiourtzoglou.

    Tip 2

    All SortedMap implementation classes should provide four “standard” constructors as the following:

    • A void (no arguments) constructor, which creates an empty SortedMap sorted according to the natural ordering of its keys.
      1 SortedMap sortedMap= new TreeMap();
    • A constructor with a single argument of type Comparator, which creates an empty SortedMap sorted according to the specified Comparator.
      1 Comparator comparator = new MyComparator();
      2 SortedMap sortedMap = new TreeMap(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.
      1 Map map = new HashMap();
      2 SortedMap sortedMap = new TreeMap(map);
    • A constructor with a single argument of type SortedMap, which creates a new SortedMap with the same key-value mappings and the same ordering as the input SortedMap.
      1 SortedMap sortedMap= new TreeMap();
      2 SortedMap newSortedMap = new TreeMap(sortedMap);

    1. SortedMap Operations:

    The SortedMap interface provides operations for normal Map operations and for the following:

    • Range view — performs arbitrary range operations on the SortedMap
      1. subMap(K fromKey, K toKey): Returns a view of the portion of this Map whose keys range from fromKey, inclusive, to toKey, exclusive.
      2. headMap(K toKey): Returns a view of the portion of this Map whose keys are strictly less than toKey.
      3. tailMap(K fromKey): Returns a view of the portion of this Map whose keys are greater than or equal to fromKey.
    • Endpoints — returns the first or the last key in the SortedMap
      1. firstKey(): Returns the first (lowest) key currently in this Map.
      2. lastKey(): Returns the last (highest) key currently in this Map.
    • Comparator access — returns the Comparator, if any, used to sort the map
      1. comparator(): Returns the Comparator used to order the keys in this Map, or null if this Map uses the natural ordering of its keys.

    2. Example:

    2.1. SortMapExample.java

    01 package com.jcg.util.map;
    02  
    03 import java.util.Comparator;
    04 import java.util.HashMap;
    05 import java.util.Map;
    06 import java.util.TreeMap;
    07  
    08 /**
    09  * @author ashraf
    10  *
    11  */
    12 public class SortMapExample {
    13  
    14     /**
    15      * The main method.
    16      *
    17      * @param args the arguments
    18      */
    19     public static void main(String[] args) {
    20         //creating unsorted map of employee id as a key and employee name as a value
    21         Map unsortMap = new HashMap();
    22         unsortMap.put(10"Ashraf");
    23         unsortMap.put(5"Sara");
    24         unsortMap.put(6"Mohamed");
    25         unsortMap.put(20"Esraa");
    26         unsortMap.put(1"Bahaa");
    27         unsortMap.put(7"Dalia");
    28         unsortMap.put(8"Amira");
    29         unsortMap.put(99"Ahmed");
    30         unsortMap.put(50"Sama");
    31         unsortMap.put(2"Nada");
    32         unsortMap.put(9"Osama");
    33  
    34         System.out.println("Unsort Map......");
    35         printMap(unsortMap);
    36  
    37         // Using the default natural ordering of sorted map Integer key which implement Comparable interface
    38         System.out.println(" Sorted Map in ascending order......");
    39         Map ascSortedMap = new TreeMap();
    40         ascSortedMap.putAll(unsortMap);
    41         printMap(ascSortedMap);
    42  
    43         // Forcing the descending order by creating our own comparator then passing it to the sorted map at creation time
    44         System.out.println(" Sorted Map in descending order......");
    45         Map desSortedMap = new TreeMap(
    46                 new Comparator() {
    47  
    48                     @Override
    49                     public int compare(Integer o1, Integer o2) {
    50                         return o2.compareTo(o1);
    51                     }
    52  
    53                 });
    54         desSortedMap.putAll(unsortMap);
    55         printMap(desSortedMap);
    56  
    57     }
    58  
    59     /**
    60      * Prints the map.
    61      *
    62      * @param map the map
    63      */
    64     public static void printMap(Map map) {
    65         for (Map.Entry entry : map.entrySet()) {
    66             System.out.println("Key : " + entry.getKey() + " Value : "
    67                     + entry.getValue());
    68         }
    69     }
    70  
    71 }

    2.2. Explanation:

    Let’s suppose that we want to sort a Map which contains a group of employees according to their ids where we use the employee id as a key and the employee name as a value. After we create a SortedMap using this Map and the key of thisMap is an Integer type which implements the Comparable interface, the keys are ordered in their natural ordering. Also, we can apply the descending order by creating our own Comparator then passing it to the SortedMap at creation time.

    2.3. Output:

    01 Unsort Map......
    02 Key : 50 Value : Sama
    03 Key : 1 Value : Bahaa
    04 Key : 2 Value : Nada
    05 Key : 99 Value : Ahmed
    06 Key : 20 Value : Esraa
    07 Key : 5 Value : Sara
    08 Key : 6 Value : Mohamed
    09 Key : 7 Value : Dalia
    10 Key : 8 Value : Amira
    11 Key : 9 Value : Osama
    12 Key : 10 Value : Ashraf
    13  
    14 Sorted Map in ascending order......
    15 Key : 1 Value : Bahaa
    16 Key : 2 Value : Nada
    17 Key : 5 Value : Sara
    18 Key : 6 Value : Mohamed
    19 Key : 7 Value : Dalia
    20 Key : 8 Value : Amira
    21 Key : 9 Value : Osama
    22 Key : 10 Value : Ashraf
    23 Key : 20 Value : Esraa
    24 Key : 50 Value : Sama
    25 Key : 99 Value : Ahmed
    26  
    27 Sorted Map in descending order......
    28 Key : 99 Value : Ahmed
    29 Key : 50 Value : Sama
    30 Key : 20 Value : Esraa
    31 Key : 10 Value : Ashraf
    32 Key : 9 Value : Osama
    33 Key : 8 Value : Amira
    34 Key : 7 Value : Dalia
    35 Key : 6 Value : Mohamed
    36 Key : 5 Value : Sara
    37 Key : 2 Value : Nada
    38 Key : 1 Value : Bahaa
  • 相关阅读:
    [HAOI2011] 向量
    [HNOI2004] 树的计数
    [TJOI2009] 猜数字
    Wannafly Camp 2020 Day 6K 最大权值排列
    [HAOI2012] 容易题
    [ZJOI2008] 生日聚会
    [CQOI2007] 余数求和
    [CQOI2009] 中位数
    [SDOI2012] Longge的问题
    我的Apache又挂了之apache错误:server's fully qualified domain name, using 127.0.0.1. Set the 'ServerName'
  • 原文地址:https://www.cnblogs.com/hephec/p/4559100.html
Copyright © 2011-2022 走看看