JDK1.8对Map的最新排序方法

本文介绍两种Java中Map排序的方法,包括传统排序和利用Stream API的新排序方式,支持按值或键升序、降序排列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.传统排序:

//对值进行排序,此处为降序
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueDescending(Map<K, V> map)
    {
        List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<K, V>>()
        {
            @Override
            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2)
            {
                int compare = (o1.getValue()).compareTo(o2.getValue());
                return -compare;
            }
        });

        Map<K, V> result = new LinkedHashMap<K, V>();
        for (Map.Entry<K, V> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }

2.新排序方法:

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, boolean asc) 
    {
        Map<K, V> result = new LinkedHashMap<>();
        Stream<Entry<K, V>> stream = map.entrySet().stream();    
		if (asc) //升序
		{
			 //stream.sorted(Comparator.comparing(e -> e.getValue()))
			stream.sorted(Map.Entry.<K, V>comparingByValue())
				.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
		}
		else //降序
		{
			 //stream.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
			stream.sorted(Map.Entry.<K, V>comparingByValue().reversed())
				.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
		}
        return result;
    }

public static <K extends Comparable<? super K>, V > Map<K, V> sortByKey(Map<K, V> map, boolean asc) 
	{
        Map<K, V> result = new LinkedHashMap<>();
        Stream<Entry<K, V>> stream = map.entrySet().stream();
        if (asc) 
		{
        	stream.sorted(Map.Entry.<K, V>comparingByKey())
                .forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        }
        else 
		{
        	stream.sorted(Map.Entry.<K, V>comparingByKey().reversed())
            	.forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
		}
	    return result;
	}

3.上面的知识点补充:

jdk1.8新特性:

    a. 新增Lambda表达式和函数式接口;

    b. 新增Stream API(java.util.stream);

其他新特性见文章:https://blog.youkuaiyun.com/u014470581/article/details/54944384

 

                ---------------------------------------------欢迎关注公众号(生活不止有代码)-------------------------------------------------------

                                                                      

### JDK 1.8 中实现分组和排序功能 在 JDK 1.8 中,`Stream API` 提供了一种强大的工具来处理集合数据。通过 `Collectors.groupingBy` 和 `Collectors.collectingAndThen` 方法可以轻松实现分组操作,而排序可以通过 `Comparator` 来完成。 #### 分组与排序的组合实现 以下是使用 `Stream API` 进行分组并按特定字段排序的一个示例: ```java import java.util.*; import java.util.stream.Collectors; class Transaction { private String type; private int value; public Transaction(String type, int value) { this.type = type; this.value = value; } public String getType() { return type; } public int getValue() { return value; } } public class Main { public static void main(String[] args) { List<Transaction> transactions = Arrays.asList( new Transaction("GROCERY", 10), new Transaction("ENTERTAINMENT", 20), new Transaction("GROCERY", 30), new Transaction("ENTERTAINMENT", 40) ); Map<String, List<Integer>> groupedTransactions = transactions.stream() .collect(Collectors.groupingBy( Transaction::getType, Collectors.mapping(Transaction::getValue, Collectors.toList()) )); System.out.println("Grouped Transactions Before Sorting: " + groupedTransactions); Map<String, List<Integer>> sortedGroupedTransactions = transactions.stream() .collect(Collectors.groupingBy( Transaction::getType, Collectors.collectingAndThen( Collectors.mapping(Transaction::getValue, Collectors.toList()), list -> list.stream().sorted(Comparator.reverseOrder()).toList() ) )); System.out.println("Sorted Grouped Transactions: " + sortedGroupedTransactions); } } ``` 上述代码展示了如何利用 `groupingBy` 对交易记录按照类型 (`type`) 进行分组,并对每组中的数值 (`value`) 按照降序排列[^1]。 #### 关键点解析 - **分组**:`Collectors.groupingBy(classifier)` 是用于将流中的元素根据指定的标准分类到不同的桶中。 - **映射**:`Collectors.mapping(mapper, downstream)` 将每个输入元素转换为另一种形式后再收集。 - **排序**:对于列表类型的下游收集器,可以直接在其基础上应用 `stream()` 并调用 `sorted()` 函数进行排序[^2]。 此方法不仅能够满足基本需求,还具有良好的可扩展性和灵活性。 ---
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值