java8集合流遍历,Java 8流:遍历列表映射

I have the following Object and a Map:

MyObject

String name;

Long priority;

foo bar;

Map> anotherHashMap;

I want to convert the Map in another Map. The Key of the result map is the key of the input map. The value of the result map ist the Property "name" of My object, ordered by priority.

The ordering and extracting the name is not the problem, but I could not put it into the result map. I do it the old Java 7 way, but it would be nice it is possible to use the streaming API.

Map> result = new HashMap<>();

for (String identifier : anotherHashMap.keySet()) {

List generatedList = anotherHashMap.get(identifier).stream()...;

teaserPerPage.put(identifier, generatedList);

}

Has anyone an idea? I tried this, but got stuck:

anotherHashMap.entrySet().stream().collect(Collectors.asMap(..., ...));

解决方案

Map> result = anotherHashMap

.entrySet().stream() // Stream over entry set

.collect(Collectors.toMap( // Collect final result map

Map.Entry::getKey, // Key mapping is the same

e -> e.getValue().stream() // Stream over list

.sorted(Comparator.comparingLong(MyObject::getPriority)) // Sort by priority

.map(MyObject::getName) // Apply mapping to MyObject

.collect(Collectors.toList())) // Collect mapping into list

);

Essentially, you stream over each entry set and collect it into a new map. To compute the value in the new map, you stream over the List from the old map, sort, and apply a mapping and collection function to it. In this case I used MyObject::getName as the mapping and collected the resulting names into a list.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值