通过使用java 8流对其进行排序,将集合转换为Map [英] Converting a collection to Map by sorting it using java 8 streams

查看:1398
本文介绍了通过使用java 8流对其进行排序,将集合转换为Map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,我需要自定义排序,然后将其转换为地图与它的Id vs名称地图。下面是将执行作业的代码,但是

I have a list that I need to custom sort it first and then convert it to a map with it's Id vs name map. Here is the code that will do the job but ---

Map<Long, String> map = new LinkedHashMap<>();
list.stream().sorted(Comparator.comparing(Building::getName)).forEach(b-> map.put(b.getId(), b.getName()));

我认为这将完成这项工作,但我想知道我是否可以避免在这里创建链接哈希映射

I think this will do the job but I wonder if I can avoid creating linked hash map here and just like fancy functional programming do the job in one line?

推荐答案

你有 Collectors.toMap 为此目的:

Map<Long, String> map = 
    list.stream()
        .sorted(Comparator.comparing(Building::getName))
        .collect(Collectors.toMap(Building::getId,Building::getName));

如果您想强制实例化Map实现,请使用:

If you want to force the Map implementation that will be instantiated, use this :

Map<Long, String> map = 
    list.stream()
        .sorted(Comparator.comparing(Building::getName))
        .collect(Collectors.toMap(Building::getId,
                                  Building::getName,
                                  (v1,v2)->v1,
                                  LinkedHashMap::new));

这篇关于通过使用java 8流对其进行排序,将集合转换为Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆