Java Map Sort sortByValues(Map map, final Comparator comp)

Here you can find the source of sortByValues(Map map, final Comparator comp)

Description

sort By Values

License

Open Source License

Declaration

public static <A, B> Map<A, B> sortByValues(Map<A, B> map,
            final Comparator<B> comp) 

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;
import java.util.Map.Entry;

public class Main {
    public static <A, B> Map<A, B> sortByValues(Map<A, B> map,
            final Comparator<B> comp) {
        List<Map.Entry<A, B>> entries = new LinkedList<Entry<A, B>>(
                map.entrySet());// w  w w.  ja  va  2s .co m
        Collections.sort(entries, new Comparator<Map.Entry<A, B>>() {
            @Override
            public int compare(Entry<A, B> o1, Entry<A, B> o2) {
                return comp.compare(o1.getValue(), o2.getValue());
            }
        });
        Map<A, B> out = new LinkedHashMap<A, B>();
        for (Map.Entry<A, B> e : entries) {
            out.put(e.getKey(), e.getValue());
        }
        return out;
    }
}

Related

  1. sortByValueAscending(Map map)
  2. sortByValueDESC(Map map)
  3. sortByValueDescending( Map map)
  4. sortByValues( Map map)
  5. sortByValues(final Map map)
  6. sortByValues(Map map)
  7. sortByValues(Map map)
  8. sortByValues(Map map)
  9. sortByValues(Map map)