它与java 8流API一起看起来很不错:
java.util.Collection<String> idToDelete =
currentB.stream() //get the stream
.filter(b -> !newA.contains(b.getA())) // filter those b, whose A is in newA
.map(b -> b.getA().id) // map transform to get just an Id (you can use just getA() here)
.collect(Collectors.toList()); // finally transform back to list
java.util.Collection<String> idToAdd =
newA.stream() // again get stream
.filter(
// this is a little bit fancy...
// only leave those A, for which currentB doesn't contain element, that has getA() equals to that A
a -> currentB.stream().noneMatch(
b -> b.getA().equals(a)
)
)
.map(a -> a.id) // again get id
.collect(Collectors.toList()); // transform to list
[编辑:]
如果你查看番石榴的源代码,你会发现
transform
只需用一个转换函数包装现有的一个。因此,番石榴基本上与java8流一样工作。所以你可以像以前一样使用变换。如果绝对不想这样做,这是番石榴的完整例子:
Function<B, A> BtoA = new Function<B, A>() {
public A apply(final B b) {
return b.getA();
}
};
Function<A, String> aToId = new Function<A, String>() {
public String apply(final A a) {
return a.getId();
}
};
java.util.Collection<B> bToDelete = Collections2.filter(currentB, Predicates.compose(Predicates.not(Predicates.in(newA)), BtoA));
//without transform, looks ugly
java.util.Collection<A> aToAdd = Collections2.filter(newA, new Predicate<A>() {
@Override
public boolean apply(final A a) {
return !Iterables.any(currentB, new Predicate<B>() {
@Override
public boolean apply(B b) {
return b.getA().equals(a);
}
});
}
});
// this is essentially the same, you can safely use transform
//java.util.Collection<A> aToAdd = Collections2.filter(newA, Predicates.not(Predicates.in(Collections2.transform(currentB, BtoA))));
java.util.Collection<String> idToDelete = Collections2.transform(bToDelete, Functions.compose(aToId, BtoA));
java.util.Collection<String> idToAdd = Collections2.transform(aToAdd, aToId);
System.out.println("Old B: " + idToDelete);
System.out.println("New A: " + idToAdd);