Transforming/Filtering 使用 Guava 集合的自定义对象列表
Transforming/Filtering a list of custom objects to another using Guava collections
我正在尝试将下面的逻辑转换为可能使用 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 只是一个 class,具有 Long appId 和 Date createdOn。
是否可以将此特定逻辑转换为基于 Guava 的逻辑。
代码说明:从Detail对象列表中,找到每个appId最近创建的对象。如果一个 appId 有多个详细信息,则只选择最新的一个。
只能使用Java7
我认为您无法使用 Guava 中的过滤器或转换方法以某种方式重写此代码,但您肯定可以从其他 Guava 方法中获益。
首先,使用Multimaps.index(Iterable<V> values, Function<? super V, K> keyFunction)
方法你可以清楚地表明你想通过appId将detailList分成多个集合:
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;
我正在尝试将下面的逻辑转换为可能使用 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 只是一个 class,具有 Long appId 和 Date createdOn。
是否可以将此特定逻辑转换为基于 Guava 的逻辑。
代码说明:从Detail对象列表中,找到每个appId最近创建的对象。如果一个 appId 有多个详细信息,则只选择最新的一个。
只能使用Java7
我认为您无法使用 Guava 中的过滤器或转换方法以某种方式重写此代码,但您肯定可以从其他 Guava 方法中获益。
首先,使用Multimaps.index(Iterable<V> values, Function<? super V, K> keyFunction)
方法你可以清楚地表明你想通过appId将detailList分成多个集合:
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;