Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

After groupingBy convert 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 that after groupingBy here so that that the end result is as shown below.

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

How to invoke function to convert ItemTypeA to ItemTypeB?;

like image 735
aquitted-mind Avatar asked Mar 27 '18 11:03

aquitted-mind


People also ask

How does Collector groupingBy work?

groupingBy. Returns a Collector implementing a cascaded "group by" operation on input elements of type T , grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector .

What is the use of groupingBy in Java 8?

The groupingBy() method of Collectors class in Java are used for grouping objects by some property and storing results in a Map instance.

Can we convert list to set in Java?

Given a list (ArrayList or LinkedList), convert it into a set (HashSet or TreeSet) of strings in Java. We simply create an list. We traverse the given set and one by one add elements to the list. // Set to array using addAll() method.


1 Answers

You can use Collectors.mapping:

Map<Integer,List<ItemTypeB>> output = 
    data.stream()
        .collect(Collectors.groupingBy(ItemTypeA::getId,
                 Collectors.mapping(a->convert(a),
                                    Collectors.toList())));
like image 71
Eran Avatar answered Sep 18 '22 22:09

Eran