【问题标题】:Java Filter a List of Model by a Property and Return the Filter Out ListJava 按属性过滤模型列表并返回过滤出列表
【发布时间】:2017-07-06 06:56:59
【问题描述】:

我有一个模型类的列表。它包含两个字段:

Class Model {
    String id;
    String type;
}

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

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

我考虑过构建一个Map<String, Set<String>> 结构,type 作为键,Set<id> 作为值,当我迭代List<Model> 时,我检查Map 是否包含我看到的键,如果是,则将id 添加到Set,如果添加成功,则表示它没有区别,我将它们添加到结果Map<String, List<Modal>>

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

【问题讨论】:

  • 你的问题很混乱。尝试简化和明确你的意思。也许用代码以外的东西来解释你的问题。
  • 你要找的东西一点都不难,但到目前为止你有什么尝试?自己写一些代码,遇到问题再回来。我们不会为你编写代码。

标签: java arraylist lambda hashmap set


【解决方案1】:

怎么样

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=[Model{id='2', type='type2'}, Model{id='3', type='type2'}]}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    • 2017-05-05
    • 2019-12-26
    • 2020-04-05
    • 2014-08-22
    相关资源
    最近更新 更多