Java HashMap Sort sortByComparator(HashMap unsortMap, final boolean ascendingorder)

Here you can find the source of sortByComparator(HashMap unsortMap, final boolean ascendingorder)

Description

sort By Comparator

License

Open Source License

Declaration

public static HashMap<String, Integer> sortByComparator(HashMap<String, Integer> unsortMap,
            final boolean ascendingorder) 

Method Source Code


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

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

public class Main {
    public static HashMap<String, Integer> sortByComparator(HashMap<String, Integer> unsortMap,
            final boolean ascendingorder) {

        List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());

        // Sorting the list based on values
        Collections.sort(list, new Comparator<Entry<String, Integer>>() {
            public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
                if (ascendingorder) {
                    return o1.getValue().compareTo(o2.getValue());
                } else {
                    return o2.getValue().compareTo(o1.getValue());

                }//from ww  w  . j  ava  2  s. c  o m
            }
        });

        // Maintaining insertion order with the help of LinkedList
        HashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        for (Entry<String, Integer> entry : list) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        return sortedMap;
    }
}

Related

  1. getSortedColors(HashMap colors)
  2. getSortedHashMapKeyset(Map sorting)
  3. getSortedLinkedHashMap(Map bitCounts, Comparator comparator)
  4. sortByValue(HashMap map)
  5. sortedScoreMap(HashMap unSortedMap)
  6. sortHashMapByKeys(HashMap passedMap, boolean ascending)
  7. sortHashMapByValues( HashMap> passedMap, String key0)

  8. HOME | Copyright © www.java2s.com 2016