Home > Back-end >  How get a Map<String, List<Object>> from a Stream in Java 8
How get a Map<String, List<Object>> from a Stream in Java 8

Time:10-13

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.

CodePudding user response:

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.

  • Related