【问题标题】:Transforming/Filtering a list of custom objects to another using Guava collections使用 Guava 集合将自定义对象列表转换/过滤为另一个
【发布时间】:2016-11-18 02:18:52
【问题描述】:

我正在尝试将以下逻辑转换为可能使用 Guava 集合,但无法确定哪个最适合 - 过滤或转换。即使多步骤如何确保发生过滤的列表建立在自身之上。

Map<Long, Detail> map = new HashMap<>();
for (Detail detail : detailList) {
  if (map.containsKey(detail.getAppId())) {
      Detail currentDetail = map.get(detail.getAppId());
      if (detail.getCreatedOn().before(currentDetail.getCreatedOn())) {
          continue;
      }
  }
  map.put(detail.getAppId(), detail);
}
return new ArrayList<>(map.values());

Detail 只是一个具有 Long appId 和 Date createdOn 的类。

是否有可能将此特定逻辑转换为基于 Guava 的逻辑。

代码说明:从 Detail 对象列表中,找到每个 appId 最近创建的对象。如果 appId 包含多个详细信息,则只选择最新的。

只能使用 Java 7

【问题讨论】:

  • 这真的不能作为一个视图集合工作,这是 Guava 内置的。 这些操作中的任何一个都不允许您以任何方式组合值。您当前的方法可能是自 Java 7 以来最好的方法。(如果您有 Java 8,那可能是另一回事了。)

标签: java list dictionary collections guava


【解决方案1】:

我认为您无法使用 Guava 中的 filter 或 transform 方法重写此代码,但您当然可以从其他 Guava 方法中受益。

首先,使用Multimaps.index(Iterable&lt;V&gt; values, Function&lt;? super V, K&gt; keyFunction) 方法可以清楚地表明您想将detailList 分解为appId 的集合数:

Multimap<Integer, Detail> detailsByAppId = Multimaps.index(detailList,
        new Function<Detail, Integer>() {
          @Override
          public Integer apply(Detail detail) {
            return detail.getAppId();
          }
        }
);

然后你可以遍历这个集合集合,并在每个集合中找到最新的细节:

List<Detail> latestDetails = new ArrayList<Detail>();
for (Collection<Detail> detailsPerAppId : detailsByAppId.asMap().values()) {
  Detail latestDetail = Collections.max(detailsPerAppId, new Comparator<Detail>() {
    @Override
    public int compare(Detail d1, Detail d2) {
      return d1.getCreatedOn().compareTo(d2.getCreatedOn());
    }
  });
  latestDetails.add(latestDetail);
}
return latestDetails;

【讨论】:

  • 不错的答案。但是,如果您为 FunctionComparator 使用 lambda 表达式而不是匿名类,您的代码会更短、更清晰、更优雅。比较器也可以写成Comparator.comparing(Detail::getCreatedOn)
  • @Lii 你是对的,但是问题的作者没有提到他正在使用什么版本的 java,并且想使用 Guava 中的过滤器或转换方法而不是 Stream API,所以我认为他是使用 Java 6 或 7。
  • 不幸的是,我只能使用 Java 7,看来这是我能得到的唯一接近的答案。
猜你喜欢
  • 2013-10-10
  • 1970-01-01
  • 2013-08-14
  • 2012-11-20
  • 1970-01-01
  • 2015-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多