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

3
  • 1
    Collectors.toMap( d -> Integer.toString(d.getId()) , details->details) is not enough? Commented Mar 26, 2021 at 21:57
  • I tried this but not able to find getId() Commented Mar 27, 2021 at 2:04
  • A minimal reproducible example would help us help you. Commented Mar 27, 2021 at 11:41

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.