I've got an object as below
public class Model {
private String key;
private String data1;
private String data2;
private String data3;
// getters
}
A list of these Models is being returned via the data layer.
Now I want to create a Map<String, List<Model>> with the key being the "key" field in the Modelclass.
There are multiple duplicate "key"s with different data values.
I have the below existing solution but need a simpler and better way. Haven't used Java 8 extensively so not quite familiar with most of the methods and need a solution soon as I don't have time to research.
List<Model> models = modelRepo.getAllModels();
Set<String> keys = models.stream().map(Model::getKey).collect(Collectors.toSet());
Map<String, List<Model>> result = new HashMap<>();
keys.stream().forEach(key -> {
List<Model> modelList = new ArrayList<>();
models.stream().forEach(model -> {
if (model.getKey().equals(key)) {
modelList.add(model);
}
});
result.put(key, modelList);
});