Java Map Sort sort(Map map)

Here you can find the source of sort(Map map)

Description

sort

License

Open Source License

Declaration

public static <K extends Comparable<K>, V> LinkedHashMap<K, V> sort(Map<K, V> map) 

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<K>, V> LinkedHashMap<K, V> sort(Map<K, V> map) {
        LinkedHashMap<K, V> returnMap = new LinkedHashMap<K, V>();
        List<K> keys = new LinkedList<K>(map.keySet());
        Collections.sort(keys);//from  w  w w .  j a  v  a2  s. c  o  m
        for (K key : keys) {
            returnMap.put(key, map.get(key));
        }
        return returnMap;
    }

    public static <K, V> LinkedHashMap<K, V> sort(Map<K, V> map, Comparator<K> comparator) {
        LinkedHashMap<K, V> returnMap = new LinkedHashMap<K, V>();
        List<K> keys = new LinkedList<K>(map.keySet());
        Collections.sort(keys, comparator);
        for (K key : keys) {
            returnMap.put(key, map.get(key));
        }
        return returnMap;
    }

    public static <K extends Comparable<K>, V, L extends LinkedHashMap<K, V>> L sort(L map) {
        @SuppressWarnings("unchecked")
        L returnMap = (L) map.clone();
        returnMap.clear();
        List<K> keys = new LinkedList<K>(map.keySet());
        Collections.sort(keys);
        for (K key : keys) {
            returnMap.put(key, map.get(key));
        }
        return returnMap;
    }

    public static <K, V, L extends LinkedHashMap<K, V>> L sort(L map, Comparator<K> comparator) {
        @SuppressWarnings("unchecked")
        L returnMap = (L) map.clone();
        returnMap.clear();
        List<K> keys = new LinkedList<K>(map.keySet());
        Collections.sort(keys, comparator);
        for (K key : keys) {
            returnMap.put(key, map.get(key));
        }
        return returnMap;
    }
}

Related

  1. sort(Map map, Comparator> comparator)
  2. sort(Map map)
  3. sort(Map src)
  4. sort(T map, Comparator> c)