Java按属性筛选模型列表并返回筛选出列表

时间:2017-07-06 06:57:00

标签: java arraylist lambda hashmap set

我有一个Model类列表。它包含两个字段:

Class Model {
    String id;
    String type;
}

我有一个Map结构: Map<String, List<Model>>每个String表示映射到List<Model>的名称。

现在我想检查名称是否有明确的List<Model>。仅当每个模型具有不同类型时,列表才会考虑不同。如果有Modal A ("abc", "green"),那么如果我看到Modal B ("dbc", "green")Modal C("drrt", "green"),那么Modal B, Modal C就没有区别,我想存储Name和{{1 }},并返回Modal B, Modal C,它代表具有非独特Map<String, List<Modal>>列表的名称;

我考虑构建List<Model>结构,Map<String, Set<String>>作为键,type作为值,当我迭代Set<id>时,我会检查List<Model> 1}}包含我见过的密钥,如果是,则将Map添加到id,如果添加成功,则意味着它是非独特的,我会将它们添加到结果{{1 }}。

但是,使用Java库或Lambda等,是否有另一种方式,或更优雅/简单/有效的方式?请帮忙~~~

1 个答案:

答案 0 :(得分:0)

怎么样

public class Main {

    public static void main(String[] args) {
        Map<String, List<Model>> map = Stream.of(
                new Model("1", "type1"),
                new Model("2", "type2"),
                new Model("3", "type2")
        )
                .collect(groupingBy(m -> "name"));

        Map<String, List<Model>> dupes = map.entrySet().stream()
                .flatMap(e -> e.getValue().stream()
                        .collect(groupingBy(Model::getType))
                        .entrySet().stream()
                        .filter(e1 -> e1.getValue().size() > 1)
                        .map(e1 -> new SimpleImmutableEntry<>(e.getKey(), e1.getValue())))
                .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));

        System.out.println(dupes);

    }

    private static class Model {
        private final String id;
        private final String type;

        public Model(String id, String type) {
            this.id = id;
            this.type = type;
        }

        public String getId() {
            return id;
        }

        public String getType() {
            return type;
        }

        @Override
        public String toString() {
            return "Model{" +
                    "id='" + id + '\'' +
                    ", type='" + type + '\'' +
                    '}';
        }
    }
}

打印{name = [型号{id =&#39; 2&#39;,type =&#39; type2&#39;},型号{id =&#39; 3&#39;,type =&# 39; TYPE2&#39;}]}

相关问题