map 속성 에 따라 정렬, map 앞 n 개 후 n 개 꺼 내기

19976 단어 JAVA자바
map 키 오름차 순 정렬
	/**
     * map   key     
     *
     * @param map
     * @return
     */
    private Map<String, Object> sortByKey(Map<String, Object> map) {
     
        Map<String, Object> result = new LinkedHashMap<>(map.size());
        map.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        return result;
    }

map 속성 에 따라 정렬, map 전 n 개, 후 n 개 꺼 내기
/**
 * map  value  
 * flag = 1   
 * flag = 0   
 *
 * @param map
 * @param flag
 * @return
 */
public static <K, V extends Comparable<? super V>> LinkedHashMap<K, V> sortByValue(Map<K, V> map, int flag) {
     
    LinkedHashMap<K, V> sortMap = new LinkedHashMap<>();
    if (flag == 1) {
     
        map.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue)).forEach(entry -> sortMap.put(entry.getKey(), entry.getValue()));
    } else {
     
        map.entrySet().stream().sorted((o1, o2) -> o2.getValue().compareTo(o1.getValue())).forEach(entry -> sortMap.put(entry.getKey(), entry.getValue()));
    }
    return sortMap;
}
 
/**
 *   map n 
 *
 * @param map
 * @param length
 * @return
 */
public LinkedHashMap<String, Double> subMap(LinkedHashMap<String, Double> map, int length) {
     
    List<Map.Entry<String, Double>> lists = new ArrayList<>(map.entrySet());
    LinkedHashMap<String, Double> sortedMap = new LinkedHashMap<>();
    if (lists.size() >= length) {
     
        for (Map.Entry<String, Double> set : lists.subList(0, length)) {
     
            sortedMap.put(set.getKey(), set.getValue());
        }
    } else {
     
        for (Map.Entry<String, Double> set : lists) {
     
            sortedMap.put(set.getKey(), set.getValue());
        }
    }
    return sortedMap;
}

/**
 *   map n 
 *
 * @param map
 * @param length
 * @return
 */
protected LinkedHashMap<Date, BigDecimal> subMap(LinkedHashMap<Date, BigDecimal> map, int length) {
     
        List<Map.Entry<Date, BigDecimal>> lists = new ArrayList<>(map.entrySet());
        LinkedHashMap<Date, BigDecimal> sortedMap = new LinkedHashMap<>();
        int size = lists.size();
        if (size >= length) {
     
            for (Map.Entry<Date, BigDecimal> set : lists.subList(size -length, size)) {
     
                sortedMap.put(set.getKey(), set.getValue());
            }
        } else {
     
            for (Map.Entry<Date, BigDecimal> set : lists) {
     
                sortedMap.put(set.getKey(), set.getValue());
            }
        }
        return sortedMap;
    }

좋은 웹페이지 즐겨찾기