After groupingBy, convert the list of objects from type A to type B

Map<Integer,List<ItemTypeA>> list = data.stream().collect(groupingBy(ItemTypeA::getId)); 

I have a function that converts ItemTypeA to ItemTypeB.

public ItemTypeB convert (ItemTypeA); 

How can I use this after groupingByhere, so that the end result will be as shown below.

Map<Integer,List<ItemTypeB>> map = data.stream().collect(groupingBy(ItemTypeA::getId), 

How to call a function to convert ItemTypeAto ItemTypeB?;

+4
source share
1 answer

You can use Collectors.mapping:

Map<Integer,List<ItemTypeB>> output = 
    data.stream()
        .collect(Collectors.groupingBy(ItemTypeA::getId,
                 Collectors.mapping(a->convert(a),
                                    Collectors.toList())));
+6
source

Source: https://habr.com/ru/post/1695411/


All Articles