简体   繁体   中英

How to extract only ID's from object after groupingBy in java 8

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> ie

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.

You need to use Collectors.mapping() . It would look like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM