Java Map Sort sortByKey(T map, final boolean descending)

Here you can find the source of sortByKey(T map, final boolean descending)

Description

sort By Key

License

Open Source License

Declaration

public static <K extends Comparable<? super K>, V, T extends Map<K, V>> T sortByKey(T map,
            final boolean descending) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class Main {
    public static <K extends Comparable<? super K>, V, T extends Map<K, V>> T sortByKey(T map) {
        return sortByKey(map, false);
    }//from   w  w  w.  j av a2  s . c om

    public static <K extends Comparable<? super K>, V, T extends Map<K, V>> T sortByKey(T map,
            final boolean descending) {
        return sort(map, new Comparator<Map.Entry<K, V>>() {
            @Override
            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
                return ((o1.getKey()).compareTo(o2.getKey()) * (descending ? -1 : 1));
            }
        });
    }

    public static <K, V, T extends Map<K, V>> T sort(T map, Comparator<Map.Entry<K, V>> c) {
        List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
        Collections.sort(list, c);
        Object result = new LinkedHashMap<>();
        for (Map.Entry<K, V> entry : list) {
            ((T) result).put(entry.getKey(), entry.getValue());
        }
        return (T) result;
    }
}

Related

  1. sortByComparatorDecreasing(Map unsortMap)
  2. sortByComparatorDouble( final Map map)
  3. sortByDescendingValues(Map unsortMap)
  4. sortByKey(final Map map, String order)
  5. sortByKey(Map map)
  6. sortByKeys( Map map)
  7. sortByKeys(Map map)
  8. sortByMap(List> lists)
  9. sortByMap(Map map, int size)