java map排序

1、按key的部分特征排序

    /**
     * 对Map>中key排序,
     * key格式为gei-0/0/12/7、gei-0/1/3/4、gei-0/1/12/6、xgei-0/1/1/49 TO-ShangLian
     * 以“/”分割,从左往右开始排序。
     *
     * @return
     */
   public static void main(String[] args) {  
        Map> performanceSlotMap = new HashMap<>();
        performanceSlotMap.put("gei-0/1/12/6", Arrays.asList("1"));
        performanceSlotMap.put("gei-0/0/12/7", Arrays.asList("1"));
        performanceSlotMap.put("xgei-0/1/1/49 TO-ShangLian", Arrays.asList("1"));
        performanceSlotMap.put("gei-0/1/3/4", Arrays.asList("1"));

        // 使用自定义的Comparator对map的键进行排序
        Map> sortedMap1 = performanceSlotMap.entrySet().stream()
                .sorted(Map.Entry.>comparingByKey(Comparator.comparing(s -> s.toString().split("/")[0])
                        .thenComparing(s -> Integer.parseInt(s.toString().split("/")[1]))
                        .thenComparing(s -> Integer.parseInt(s.toString().split("/")[2]))
                        .thenComparing(s -> s.toString().split("/")[3])
                ))
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));

        // 输出排序后的map
        System.out.println(sortedMap1);
    }


//结果
{gei-0/0/12/7=[1], gei-0/1/3/4=[1], gei-0/1/12/6=[1], xgei-0/1/1/49 TO-ShangLian=[1]}

@Data
@AllArgsConstructor
public class DailyDataChartVo {

    /**
     * 日期
     */
    private LocalDate date;

    /**
     * 今日营收
     */
    private BigDecimal revenue;
}
//List排序
//按日期排序
List list = list.stream()
        .sorted(Comparator.comparing(DailyDataChartVo::getDate))
        .collect(Collectors.toList());
//按日期排序后,逆序
List list = list.stream()
        .sorted(Comparator.comparing(DailyDataChartVo::getDate).reversed())
        .collect(Collectors.toList());
//按日期排序后,再按金额排序
List list = list.stream()
        .sorted(Comparator.comparing(DailyDataChartVo::getDate)
                .thenComparing(DailyDataChartVo::getRevenue))
        .collect(Collectors.toList());
//按金额排序,排序时过滤Null值(如果排序的字段为null,NPE)
List list = list.stream()
        .filter(c -> Objects.nonNull(c.getRevenue()))
        .sorted(Comparator.comparing(DailyDataChartVo::getRevenue))
        .collect(Collectors.toList());
//按金额排序,Null值排在最前面
List list = list.stream()
        .sorted(Comparator.comparing(DailyDataChartVo::getRevenue,
                Comparator.nullsFirst(BigDecimal::compareTo)))
        .collect(Collectors.toList());
//注意Comparator.nullsFirst的方法引用中,比较的字段是BigDecimal类型的,如果前后类型不一致,会报错:Non-static method cannot be referenced from a static context
//按金额排序,Null值排在最后面
List list = list.stream()
        .sorted(Comparator.comparing(DailyDataChartVo::getRevenue,
                Comparator.nullsLast(BigDecimal::compareTo)))
        .collect(Collectors.toList());
        
//Map排序
//按key排序
Map map = map.entrySet()
        .stream()
        .sorted(Map.Entry.comparingByKey())
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (c1, c2) -> c1, LinkedHashMap::new));
//将map转换成流,在流中对元素进行排序,排序后,再用LinkedHashMap收集来保留顺序
public static , V> Comparator> comparingByKey() {
    return (Comparator> & Serializable)
        (c1, c2) -> c1.getKey().compareTo(c2.getKey());
}
Map.Entry.comparingByKey():对任意的c1, c2进行比较,然后将结果强制转换成一个可序列化的Comparator>Collectors.toMap()基础
//按key排序后,逆序
Map map = map.entrySet()
        .stream()
        .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (c1, c2) -> c1, LinkedHashMap::new));
//按value排序
Map map = map.entrySet()
        .stream()
        .sorted(Map.Entry.comparingByValue())
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (c1, c2) -> c1, LinkedHashMap::new));
List list = userMapper.selectAll(param);
// List 转 Map
Map> idMap = list.stream().collect(Collectors.groupingBy(User::getId));
// 排序方式1 Map 根据 id 从小到大排序(降序修改(e1, e2) e1 e2 的位置换一换即可)
Map> sort1IdMap = idMap.entrySet().stream().sorted((e1, e2) ->
             Integer.compare(Integer.parseInt(e1.getKey()),         
             Integer.parseInt(e2.getKey())))
             .collect(Collectors.toMap(Map.Entry::getKey, 
                Map.Entry::getValue, 
                (e1, e2) -> e1, 
                LinkedHashMap::new));
 
// 排序方式2 
Map> sort2IdMap = idMap.entrySet().stream()
        .sorted(Map.Entry.>comparingByKey().reversed())
            .forEachOrdered(x -> sortMap.put(x.getKey(),x.getValue()));
 
Map> sort22IdMap = idMap.entrySet().stream()
        .sorted(Map.Entry.comparingByKey())
            .forEachOrdered(x -> sortMap.put(x.getKey(),x.getValue()));
 
//进阶
 
// Map 根据 另一个 Map 排序
Map initMap = new LinkedHashMap<>();
initMap.put("张三",3);
initMap.put("李四",2);
initMap.put("王五",1);
 
// initMap 根据value排序
Map m1 = initMap.entrySet().stream()
    .sorted((e1, e2) -> Integer.compare(e1.getValue(), e2.getValue()))
        .collect(Collectors.toMap(Map.Entry::getKey,
            Map.Entry::getValue,(e1, e2) -> e1,
                LinkedHashMap::new));
 
// name 作为key的Map
Map> nameMap = list.stream().collect(Collectors.groupingBy(User::getName));
 
// nameMap 根据 ml的key值(name)进行排序
Map> sortOtherMap = nameMap.entrySet().stream()
    .sorted((e1, e2) -> Integer.compare(m1.get(e1.getKey()), m1.get(e2.getKey())))
        .collect(Collectors.toMap(Map.Entry::getKey,
                                Map.Entry::getValue,
                                (e1, e2) -> e1,
                                LinkedHashMap::new));
 
 

你可能感兴趣的:(java)