从List <Object>获取Map <String,List <Object >>,其中键是对象的字段之一

我有一个对象如下

public class Model {
  private String key;
  private String data1;
  private String data2;
  private String data3;
}

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 Model class. 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.

Map<String, List<Model>> result = new HashMap<>();
List<Model> models = modelRepo.getAllModels();
Set<String> keys = models.stream().map(Model::getKey).collect(Collectors.toSet());
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);
});
评论
  • 菊花残
    菊花残 回复

    Use groupingBy for grouping Models by key

    Map<String, List<Model>> results = models.stream()
            .collect(Collectors.groupingBy(Model::getKey,
                     Collectors.mapping(d-> d, Collectors.toList())));