【问题标题】:Elegant solution for filtering a list to be unique for given object attribute过滤列表以对给定对象属性唯一的优雅解决方案
【发布时间】:2014-06-17 21:51:15
【问题描述】:

我有一个扁平化的多映射(一个列表)对象,我想将其转换为一个列表,其中一个“关键”属性/字段(例如下面的 name)在所有条目中是唯一的.

如果多个条目具有相同的键(name),则应选择具有最大 creationDate 字段的条目。

示例:

List<Object> myList =
[
  {name="abc", age=23, creationDate = 1234L},
  {name="abc", age=12, creationDate = 2345L},
  {name="ddd", age=99, creationDate = 9999L}
]

应转换为:

List<Object> = 
[
  {name="abc", age=12, creationDate = 2345L},
  {name="ddd", age=99, creationDate = 9999L}
]

有没有一种优雅的方法(可能使用 Guava 库?)在 Java 中解决这个问题?我意识到我可以尝试使用带有 name 的 HashMap 作为键来查找所有唯一条目,但我觉得有更好的方法来解决这个问题。

谢谢!

【问题讨论】:

    标签: java guava


    【解决方案1】:

    如果您有可能使用 Java 8,我会推荐 Streams,因为其他答案已经告诉您。 如果没有,你可以选择这样的东西。

    首先您按creationDate 对List 进行降序排序。然后你创建一个 TreeSet 女巫将所有同名的人视为平等。因此,只会添加第一个(最高的)creationDate,而忽略其他的。

    List<Person> persons = new ArrayList<>();
    persons.add(new Person("abc", 23, 1234L));
    persons.add(new Person("abc", 12, 2345L));
    persons.add(new Person("def", 99, 9999L));
    
    Collections.sort(persons, new Comparator<Person>() {
        public int compare(Person o1, Person o2) {
                return (int) (o2.creationDate - o1.creationDate);
        }
    });
    
    Set<Person> personsHashed = new TreeSet<>(new Comparator<Person>() {
        public int compare(Person o1, Person o2) {
            return o2.name.compareTo(o1.name);
        }
    });
    personsHashed.addAll(persons);
    

    【讨论】:

    • 太棒了!谢谢!我没有可用的 Java 8,但这个解决方案非常简洁/易读。我可能会评论 TreeSet 只选择第一个值的副作用(我不知道)。
    【解决方案2】:

    这是否被认为是优雅是相当主观的,但这里是:

    static List<Person> byName(Collection<Person> persons) {
        Map<String, Person> personsByName = persons.stream().collect(
            Collectors.groupingBy(Person::getName,
                Collectors.collectingAndThen(
                    Collectors.maxBy(
                        Comparator.comparingLong(Person::getCreationDate)),
                    p -> p.get())));
        return new ArrayList<Person>(personsByName.values());
    }
    

    您可以通过对 Collectors 和 Comparator 的方法使用静态导入使其更具可读性,例如:

    import static java.util.stream.Collectors.collectingAndThen;
    import static java.util.stream.Collectors.groupingBy;
    import static java.util.stream.Collectors.maxBy;
    import static java.util.Comparator.comparingLong;
    

    那么代码可以稍微缩短为:

    static List<Person> byName(Collection<Person> persons) {
        Map<String, Person> personsByName =
            persons.stream().collect(
                groupingBy(Person::getName, collectingAndThen(
                    maxBy(comparingLong(Person::getCreationDate)),
                    p -> p.get())));
        return new ArrayList<Person>(personsByName.values());
    }
    

    【讨论】:

      【解决方案3】:

      在 Java 8 中,您可以使用新的 Streaming API 将集合 Stream 它通过过滤器,然后生成您的结果。那应该能够满足您的需求。

      或者,您已经考虑将它们放入 HashMap 的想法似乎非常简单,并且会提供您需要的行为。我不会尝试过度思考这个:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-05
        • 1970-01-01
        • 2011-04-01
        • 2022-07-06
        • 2018-04-28
        • 1970-01-01
        相关资源
        最近更新 更多