优雅的解决方案,用于过滤列表以使其对于给定的对象属性是唯一的 [英] Elegant solution for filtering a list to be unique for given object attribute

查看:42
本文介绍了优雅的解决方案,用于过滤列表以使其对于给定的对象属性是唯一的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a flattened multi-map (a list) of objects which I would like to convert to a list where a 'key' attribute / field (e.g. name below) is unique amongst all entries.

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

In the case where multiple entries have the same key (name) the entry with the largest creationDate field should be picked.

示例:

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作为查找所有唯一条目的键,但是我感觉有解决此问题的更好方法.

Is there an elegant way (possibly using Guava libraries?) to solve this in Java? I realize I can just try and use a HashMap with name as the key to find all unique entries, but I get the feeling there is a better way to solve this.

谢谢!

推荐答案

如果您有可能使用Java 8,我建议您使用Streams作为其他已经回答的答案. 如果没有的话,你可以选择这样的东西.

If you have the possibility to work with Java 8 I would recommend Streams as the other answers allready told. If not you can go with something like this.

首先,对由creationDate发出的List进行排序.然后,您创建一个TreeSet女巫,将具有相同名称的所有Person都视为相等.因此,将仅添加第一个(最高)creationDate,而忽略其他的.

First you sort the List desending by the creationDate. Then you create a TreeSet witch treats all Persons with same name as equal. Therefore only the first (highest) creationDate will be added and further ones ignored.

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);

这篇关于优雅的解决方案,用于过滤列表以使其对于给定的对象属性是唯一的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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