簡體   English   中英

如何從列表中獲取最新對象的列表

[英]How to get the list of latested objects from a list

我有一個對象列表(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 為每個“名稱”提取 A 類列表。

我,e,預期輸出是 -

List [
    A ("a", 03-Jan-2017),
    A ("b", 07-Jan-2017),
    .
    .
    .
    A ("x", 07-Jan-2017)
    ]
yourList.stream()
        .collect(Collectors.groupingBy(
               A::getName,
               Collectors.collectingAndThen(
                      Collectors.maxBy(Comparator.comparing(A::getCreatedDate)), 
                      Optional::get)))
        .values();

這將返回一個Collection<A> ,如果需要,您可以將其放入ArrayList中。

編輯

正如 Holger 所建議的,更好的方法是:

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

通過使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)您的列表應該根據您實現的順序進行排序。

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

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

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()) 。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM