Java8分组要映射的列表列表 [英] Java8 group a list of lists to map

查看:51
本文介绍了Java8分组要映射的列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Model 和一个具有以下签名的 Property 类:

I have a Model and a Property class with the following signatures:

public class Property {

    public String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public class Model {

    private List<Property> properties = new ArrayList<>();

    public List<Property> getProperties() {
        return properties;
    }
}

我想要 List<Model> 中的 Map<String, Set<Model>>,其中键是 Property<中的名称/代码>类.如何使用 java8 流按其 Properyes 名称对该列表进行分组?所有 Property 的名称都是唯一的.

I want a Map<String, Set<Model>> from a List<Model> where the key would be the name from the Property class. How can I can I use java8 streams to group that list by its Properyes' name? All Propertyes are unique by name.

可以在单个流中解决,还是应该以某种方式拆分它还是采用经典解决方案?

It is possible to solve in a single stream or should I split it somehow or go for the classical solution?

推荐答案

yourModels.stream()
          .flatMap(model -> model.getProperties().stream()
                  .map(property -> new AbstractMap.SimpleEntry<>(model, property.getName())))
          .collect(Collectors.groupingBy(
                Entry::getValue, 
                Collectors.mapping(
                    Entry::getKey, 
                    Collectors.toSet())));

这篇关于Java8分组要映射的列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆