[英]Cleaner way to filter collections in Java 7/Guava?
我有以下课程:
class ServiceSnapshot {
List<ExchangeSnapshot> exchangeSnapshots = ...
...
}
class ExchangeSnapshot{
Map<String, String> properties = ...
...
}
说我有ServiceSnapshots的集合,如下所示:
Collection<ServiceSnapshot> serviceSnapshots = ...
我想过滤该集合,以便生成的ServiceSnapshots集合仅包含包含ExchangeSnapshots的ServiceSnapshots,其中ExchangeSnapshots上的属性与给定的String匹配。
我有以下未经测试的代码,只是想知道是否有更清洁/更易读的方法来执行此操作,使用Java 7,如有必要,也许使用Google Guava?
Updtae:还请注意,我下面提供的代码示例不适合我的用途,因为我使用的是iterator.remove()来过滤集合。 事实证明,我不能这样做,因为它正在修改基础集合,这意味着由于以前的调用将它们从集合中删除,因此对下面方法的后续调用导致快照越来越少-这不是我想要的。
public Collection<ServiceSnapshot> getServiceSnapshotsForComponent(final String serviceId, final String componentInstanceId) {
final Collection<ServiceSnapshot> serviceSnapshots = getServiceSnapshots(serviceId);
final Iterator<ServiceSnapshot> serviceSnapshotIterator = serviceSnapshots.iterator();
while (serviceSnapshotIterator.hasNext()) {
final ServiceSnapshot serviceSnapshot = (ServiceSnapshot) serviceSnapshotIterator.next();
final Iterator<ExchangeSnapshot> exchangeSnapshotIterator = serviceSnapshot.getExchangeSnapshots().iterator();
while (exchangeSnapshotIterator.hasNext()) {
final ExchangeSnapshot exchangeSnapshot = (ExchangeSnapshot) exchangeSnapshotIterator.next();
final String foundComponentInstanceId = exchangeSnapshot.getProperties().get("ComponentInstanceId");
if (foundComponentInstanceId == null || !foundComponentInstanceId.equals(componentInstanceId)) {
exchangeSnapshotIterator.remove();
}
}
if (serviceSnapshot.getExchangeSnapshots().isEmpty()) {
serviceSnapshotIterator.remove();
}
}
return serviceSnapshots;
}
使用番石榴:
Iterables.removeIf(serviceSnapshots, new Predicate<ServiceSnapshot>() {
@Override
public boolean apply(ServiceSnapshot serviceSnapshot) {
return !Iterables.any(serviceSnapshot.getExchangeSnapshots(), new Predicate<ExchangeSnapshot>() {
@Override
public boolean apply(ExchangeSnapshot exchangeSnapshot) {
String foundComponentInstanceId = exchangeSnapshot.getProperties().get("ComponentInstanceId");
return foundComponentInstanceId != null && foundComponentInstanceId.equals(componentInstanceId);
}
});
}
});
我可能有一个!
某处丢失或倒置,但是基本策略是删除没有ID匹配的任何ExchangeSnapshot
的任何ServiceSnapshot
对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.