如何从列表中获取已验证对象的列表

时间:2018-02-12 09:46:37

标签: java collections java-8 java-stream

我有一个对象列表(A类的实例):

Class A {
  private String name;
  private Date createdDate;
}

List [
A ("a", 01-Jan-2017),
A ("a", 03-Jan-2017),
A ("a", 02-Jan-2017),
A ("b", 05-Jan-2017),
A ("b", 06-Jan-2017),
A ("b", 07-Jan-2017),
.
.
.
A ("x", 02-Jan-2017),
A ("x", 05-Jan-2017),
A ("x", 06-Jan-2017),
A ("x", 07-Jan-2017)
]

如何使用最新的createdDate为每个'name'提取A类列表。

我,预期的输出是 -

List [
    A ("a", 03-Jan-2017),
    A ("b", 07-Jan-2017),
    .
    .
    .
    A ("x", 07-Jan-2017)
    ]

3 个答案:

答案 0 :(得分:3)

yourList.stream()
        .collect(Collectors.groupingBy(
               A::getName,
               Collectors.collectingAndThen(
                      Collectors.maxBy(Comparator.comparing(A::getCreatedDate)), 
                      Optional::get)))
        .values();

这将返回Collection<A>,您可以根据需要将其放入ArrayList

修改

正如霍尔格所说,更好的方法:

...
.stream()
.collect(Collectors.toMap(
               A::getName,
               Function.identity(),
               BinaryOperator.maxBy(Comparator.comparing(A::getCreatedDate))))
.values();

答案 1 :(得分:0)

通过A实施Comparable<A>,您可以根据createdDate字段定义自定义排序。

class A implements Comparable<A> {
    private String name;
    private Date createdDate;
    public A(String name, Date createdDate) {
        this.name = name;
        this.createdDate = createdDate;
    }

    @Override
    public int compareTo(A other) {
        return createdDate.compareTo(other.createdDate); // provided you're using java.util.Date here
    }

    public static void main(String[] args) {
        List<A> aList = ... // Create your list here
        Collections.sort(aList);
        System.out.println(aList);
    }
}

致电Collections.sort(aList)后,您的列表应根据您已实施的订单进行排序。

然后,只要元素的日期晚于您要检查的日期,就可以迭代已排序的列表并停止。

答案 2 :(得分:0)

这是我的例子:
首先按名称排序,然后按日期排序。

public class MainClass {
    public static void main(String[] args) {
        List<A> aList = new ArrayList<>();
        aList.add(new A("a",new Date(2017,11,3)));
        aList.add(new A("b",new Date(2017,3,3)));
        aList.add(new A("a",new Date(2017,11,9)));
        aList.add(new A("a",new Date(2017,1,23)));
        aList.add(new A("b",new Date(2017,8,15)));

        aList.stream().sorted(Comparator.comparing(A::getName).thenComparing(A::getCreateDate))
                .filter(distinctByKey(A::getName))
                .forEach(System.out::println);
    }

    private static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor)
    {
        Map<Object, Boolean> map = new ConcurrentHashMap<>();
        return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
}

示例输出:

A{name='a', createDate=Fri Feb 23 00:00:00 IRST 3917}
A{name='b', createDate=Tue Apr 03 00:00:00 IRDT 3917}

如果您需要收藏:
将foreach替换为.collect(Collectors.toList())。