转换列表< myObject>进入地图< integer,string>基于Java 8中的Max myobject属性

发布于 2025-02-03 10:46:19 字数 658 浏览 4 评论 0 原文

我有一个列表< myObject> 。它包含一个 ObjectId 的多个记录。

myObject 类看起来

class MyObject{
  int id;
  int objectId;
  String status;
  LocalDate updatedTimestamp;
}

我需要一个 map< integer,string> 带有 objectiD as key 和相应的状态作为 value

我只需要使用一个 ObjectID 的记录,其中最新的更新了Timestamp

不同的时间戳将具有不同的状态。只需要最新的。

我没有找到实现这一目标的方法。我知道我可以通过应用获得映射,通过应用 groupingby() and code> and maxby()。

请指教。

I have a List<MyObject>. It contains multiple records for one objectId.

MyObject class looks like

class MyObject{
  int id;
  int objectId;
  String status;
  LocalDate updatedTimestamp;
}

I need a Map<Integer, String> with objectId as Key and corresponding status as a Value.

I need to consider only the record for one objectId with latest updatedTimestamp.

Different timestamps will have different status. Need only the latest one.

I didn't find a way of achieving this. I know I can get Map<integer, Optional<MyObject>> by applying groupingBy() and maxBy().

Please advise.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

趁年轻赶紧闹 2025-02-10 10:46:19

可以使用collector groupingby() collecting> collectingandthen() maxby()一起完成。

collector maxby()期望A 比较器作为参数,并产生可选结果。要创建一个比较器,我们可以使用Java 8方法

List<MyObject> objects = // initializing the source list.
        
Map<Integer, String> statusByObjectId = objects.stream()
    .collect(Collectors.groupingBy(
        MyObject::getObjectId,
        Collectors.collectingAndThen(
            Collectors.maxBy(Comparator.comparing(MyObject::getUpdatedTimestamp)),
            (Optional<MyObject> result) -> result.orElseThrow().getStatus())
        ));

It can be done using collector groupingBy() in conjunction with collectingAndThen() and maxBy().

Collector maxBy() expect a comparator as an argument and produces an optional result. To create a comparator, we can make use of the Java 8 method Comparator.comparing().

List<MyObject> objects = // initializing the source list.
        
Map<Integer, String> statusByObjectId = objects.stream()
    .collect(Collectors.groupingBy(
        MyObject::getObjectId,
        Collectors.collectingAndThen(
            Collectors.maxBy(Comparator.comparing(MyObject::getUpdatedTimestamp)),
            (Optional<MyObject> result) -> result.orElseThrow().getStatus())
        ));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文