[英]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.