-2

I am trying to learn java steams , To learn it better way I am trying to re-write existing code using streams . I am trying to convert List into a map using streaming as below

private Map<String, List<Details>> someMethod(
      Request request) {

   return  Optional.ofNullable(request)
            .map(request -> ((Parent) request.getProduct()).getItin())
            .map(itin -> itin.getDetailsList())
            .stream()
            .flatMap(Collection::stream)
           .collect(Collectors.toMap(Details::getId,details->details));

           

}

I want to build a map with Key as String but Details::getId is Integer . How do I convert it to String ?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724

1 Answers1

1

It is very likely, that Collectors.grouping By needs to be used here instead of toMap:

return Optional.ofNullable(request)
    .map(request -> ((Parent) request.getProduct()).getItin())
    .map(itin -> itin.getDetailsList())
    .stream()
    .flatMap(Collection::stream)
    .collect(Collectors.groupingBy(d -> Integer.toString(d.getId()))); // the value will be List<Details>
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42