map按照key,value比较

 

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class AccordingToKeyOrValueComparison {
	public static void main(String[] args) {
		Map map = new HashMap<>();

		map.put("1", "4");
		map.put("3", "3");
		map.put("2", "2");
		map.put("4", "1");

		// Map resultMap = sortMapByKey(map);
		// //按Key进行排序:1.treemap的性质
		Map resultMap = sortMapByKey2(map); // 按key进行排序:2.list,自定义比较器(排序后需要LinkedHashMap保存)
		// Map resultMap = sortMapByValue(map);
		// //按Value进行排序:list,自定义比较器

		for (Map.Entry entry : resultMap.entrySet()) {
			System.out.println(entry.getKey() + " " + entry.getValue());
		}
	}

	/**
	 * 使用 TreeMap的性质按key进行排序
	 * 
	 * @param map
	 * @return
	 */
	public static Map sortMapByKey(Map map) {
		if (map == null || map.isEmpty()) {
			return null;
		}
		// TreeMap默认用key的自然排序,所以不用声明比较器也可以实现key排序,比较器可以自定义排序规则,比如倒序
		// Map sortMap = new TreeMap();

		// TreeMap构造方法可以有比较器参数~但是比较器只能是对key进行比较
		Map sortMap = new TreeMap(new MapKeyComparator());

		sortMap.putAll(map);

		return sortMap;
	}

	/**
	 * 使用 list按key进行排序
	 * 
	 * @param map
	 * @return
	 */
	public static Map sortMapByKey2(Map map) {
		if (map == null || map.isEmpty()) {
			return null;
		}
		List> list = new ArrayList<>(map.entrySet());
		Collections.sort(list, new MapKeyComparator2());

		Map sortMap = new LinkedHashMap<>();
		Iterator> iterable = list.iterator();
		while (iterable.hasNext()) {
			Map.Entry tmpEntry = iterable.next();
			sortMap.put(tmpEntry.getKey(), tmpEntry.getValue());
		}

		return sortMap;
	}

	/**
	 * 使用 List对Map按value进行排序
	 * 
	 * @param oriMap
	 * @return
	 */
	public static Map sortMapByValue(Map oriMap) {
		if (oriMap == null || oriMap.isEmpty()) {
			return null;
		}
		// 一定是LinkedHashMap,因为LinkedHashMap保证put顺序和输出顺序一致!
		Map sortedMap = new LinkedHashMap<>();

		// map.entry把map的当节点装进list,对list排序
		List> entryList = new ArrayList<>(oriMap.entrySet());

		Collections.sort(entryList, new MapValueComparator());

		Iterator> iter = entryList.iterator();
		Map.Entry tmpEntry = null;
		while (iter.hasNext()) {
			tmpEntry = iter.next();
			sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
		}
		return sortedMap;
	}

}

class MapKeyComparator implements Comparator {

	@Override
	public int compare(String str1, String str2) {

		return str2.compareTo(str1);
	}
}

class MapValueComparator implements Comparator> {

	@Override
	public int compare(Map.Entry me1, Map.Entry me2) {

		return me1.getValue().compareTo(me2.getValue());
	}
}

class MapKeyComparator2 implements Comparator> {

	@Override
	public int compare(Map.Entry me1, Map.Entry me2) {

		return me1.getKey().compareTo(me2.getKey());
	}

}

转载:http://blog.51cto.com/13580976/2147994

public class SortMapByValueUtils {
    /**
     * needResult为true时Map按value从大到小排序,返回排序后的Map的Key组成的List
     * needResult为false时Map按value从大到小排序,返回排序后的Map的Key组成的List的反顺序
     * 根据距离、长度等进行排序,获取排序后需要的对应类
     */
    public static  List sortMapByValue(final Map oriMap,
            final boolean needResult) {
        if (oriMap == null || oriMap.isEmpty()) {
            return null;
        }
        final List sortedList = new ArrayList<>(oriMap.size());
        // map.entry把map的当节点装进list,对list排序
        final List> entryList = new ArrayList<>(oriMap.entrySet());
        entryList.sort(new MapValueComparator<>());
        final Iterator> iter = entryList.iterator();
        Map.Entry tmpEntry = null;
        while (iter.hasNext()) {
            tmpEntry = iter.next();
            sortedList.add(tmpEntry.getKey());
        }
        if (!needResult) {
            return sortedList;
        } else {
            return Lists.reverse(sortedList);
        }
    }

    private static class MapValueComparator implements Comparator> {
        @Override
        public int compare(final Map.Entry me1,
                final Map.Entry me2) {
            return me1.getValue().compareTo(me2.getValue());
        }
    }
}
float2List.sort((o1, o2) -> Double
                    .compare(MathToMath2.toPoint2d(o2).distanceTo(doorMidPoint2d),
                            MathToMath2.toPoint2d(o1).distanceTo(doorMidPoint2d)));
roomList.sort((o1, o2) -> Double.compare(o2.getArea(), o1.getArea()));

tvCabinetList.sort(Comparator.comparingDouble(o -> tvMidPointOnFloor.distanceTo(
                        o.getFurniturePlaneMidPointOnFloor())));

 tvCabinetList.sort((o1, o2) -> {
                    Double distanceMin1 = Double.MAX_VALUE;
                    double distanceMin2 = Double.MAX_VALUE;
                    for (final RoomProxy balcony : adjacentBalconyList) {
                        final double distanceToTvCabinet1 =
                                o1.getFurniturePlaneMidPointOnFloor().distanceTo(
                                        MathToMath2.toPoint2d(balcony.getPosition()));
                        final double distanceToTvCabinet2 =
                                o2.getFurniturePlaneMidPointOnFloor().distanceTo(
                                        MathToMath2.toPoint2d(balcony.getPosition()));
                        distanceMin1 = Math.min(distanceMin1, distanceToTvCabinet1);
                        distanceMin2 = Math.min(distanceMin2, distanceToTvCabinet2);
                    }
                    return distanceMin1.compareTo(distanceMin2);
                });

crossoverLineList.sort(Comparator.comparingDouble(LineSeg2d::length));

 

你可能感兴趣的:(Java开发中的问题分析)