Java Map Sort sortByComparator(Map unsortMap)

Here you can find the source of sortByComparator(Map unsortMap)

Description

sort By Comparator

License

Apache License

Declaration

private static Map<Integer, Integer> sortByComparator(Map<Integer, Integer> unsortMap) 

Method Source Code

//package com.java2s;
/*//  www .j  a v a  2 s  .  c om
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import java.util.ArrayList;

import java.util.Collections;
import java.util.Comparator;

import java.util.LinkedHashMap;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class Main {
    private static Map<Integer, Integer> sortByComparator(Map<Integer, Integer> unsortMap) {

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

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

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

        return sortedMap;
    }
}

Related

  1. sort(Map map)
  2. sort(Map src)
  3. sort(T map, Comparator> c)
  4. sortBy(Collection collection, final Map valuesMap)
  5. sortByComparator(Map unsortMap)
  6. sortByComparatorDecreasing(Map unsortMap)
  7. sortByComparatorDouble( final Map map)
  8. sortByDescendingValues(Map unsortMap)
  9. sortByKey(final Map map, String order)