0

I have the next class:

public class ExampleClass {
    
    private String title;
    private String codeResponse;
    private String fileName;
}

I need to generate a map in which the key is the filename, and the value is the list of objects that contain that filename. I did the following:

Map<String, List<ExampleClass>> mapValues = items
            .stream()
            .collect(Collectors.groupingBy(
                item -> item.getFileName(), 
                Collectors.mapping(item -> item, Collectors.toList())
            ));

But in this case I am saving in each fileName the total list of objects, including those that do not apply.

2
  • 2
    remove Collectors.mapping. groupingBy + toList will do your task Commented Oct 12, 2021 at 21:19
  • 1
    How come in this case I am saving in each fileName the total list of objects, including those that do not apply? This does not seem to be reproducible and a list of ExampleClass instances with the same fileName is returned. Commented Oct 12, 2021 at 22:29

1 Answer 1

4

All you need is Collectors.groupingBy. The instances will be placed in a list by default.

Map<String, List<ExampleClass>> mapValues = items.stream()
                .collect(Collectors.groupingBy(item->item.getFileName()));

You could also use ExampleClass::getFileName in place of the lambda. But that is a matter of personal preference.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.