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.
    1SortedMap sortedMap= new TreeMap();
  • A constructor with a single argument of type Comparator, which creates an empty SortedMap sorted according to the specified Comparator.
    1Comparator comparator = new MyComparator();
    2SortedMap 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.
    1Map map = new HashMap();
    2SortedMap 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.
    1SortedMap sortedMap= new TreeMap();
    2SortedMap 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

01package com.jcg.util.map;
02 
03import java.util.Comparator;
04import java.util.HashMap;
05import java.util.Map;
06import java.util.TreeMap;
07 
08/**
09 * @author ashraf
10 *
11 */
12public 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("\nSorted 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("\nSorted 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:

01Unsort Map......
02Key : 50 Value : Sama
03Key : 1 Value : Bahaa
04Key : 2 Value : Nada
05Key : 99 Value : Ahmed
06Key : 20 Value : Esraa
07Key : 5 Value : Sara
08Key : 6 Value : Mohamed
09Key : 7 Value : Dalia
10Key : 8 Value : Amira
11Key : 9 Value : Osama
12Key : 10 Value : Ashraf
13 
14Sorted Map in ascending order......
15Key : 1 Value : Bahaa
16Key : 2 Value : Nada
17Key : 5 Value : Sara
18Key : 6 Value : Mohamed
19Key : 7 Value : Dalia
20Key : 8 Value : Amira
21Key : 9 Value : Osama
22Key : 10 Value : Ashraf
23Key : 20 Value : Esraa
24Key : 50 Value : Sama
25Key : 99 Value : Ahmed
26 
27Sorted Map in descending order......
28Key : 99 Value : Ahmed
29Key : 50 Value : Sama
30Key : 20 Value : Esraa
31Key : 10 Value : Ashraf
32Key : 9 Value : Osama
33Key : 8 Value : Amira
34Key : 7 Value : Dalia
35Key : 6 Value : Mohamed
36Key : 5 Value : Sara
37Key : 2 Value : Nada
38Key : 1 Value : Bahaa

转载于:https://www.cnblogs.com/hephec/p/4559100.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值