gpt4 book ai didi

java - 如何在java 8中groupingBy之后仅从对象中提取ID

转载 作者:行者123 更新时间:2023-12-01 17:44:38 25 4
gpt4 key购买 nike

public class Element {

private Long id;

private String groupType;

}

I have List of Elements. List with different groupType like 'group1', 'group2' {1,group1},{2,group1},{3,group2}{4,group2}

I want to create map with two different list for each group but with the ids(Map>) not with the Element object Map>

below code is working fine for Map> i.e

Map<String, List<Element>> elementByGroup = new HashMap<>();
elementByGroup = element.stream().collect(
Collectors.groupingBy(Element::getGroupType));

How can i collect result in the form of Map< String, List < Long > >. I know by iterating Map and then iterating list we can get List of id's without java 8. However I want to do the same by manipulating with above code after groupingby function.

最佳答案

您需要使用Collectors.mapping() 。它看起来像这样

Map<String, List<Long>> idsByGroupType = 
elements.stream().collect(
Collectors.groupingBy(Element::getGroupType,
Collectors.mapping(Element::getId, Collectors.toList())));

关于java - 如何在java 8中groupingBy之后仅从对象中提取ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57152076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com