首先,我希望以前没有人问过这个问题。我看了一点,找不到合适的答案:s
我正在寻找一种在特定条件为真时将某些对象从一个集合移动到另一个集合的有效方法。
目前,我会以一种非常直接的方式进行,但我担心这可能不是最佳方式:
Collection<Object> myFirstCollection; //let's consider it instanciated and populated
Collection<Object> mySecondCollection; //same for this one
myFirstCollection.stream().forEach(o -> {
if ( conditionReturningTrue(o) ) {
mySecondCollection.add(o);
myFirstCollection.remove(o);
}
});
您知道更好/更有效的方法吗?
最佳答案
为了提高可读性,有Collection::addAll
和 Collection::removeAll
要在这种情况下使用,您的代码可以是:
// create a new Collection where you use filter to search only the Object you want
Collection<Object> filterdCollection = myFirstCollection.stream()
.filter(o -> conditionReturningTrue(o))
.collect(Collectors.toCollection(LinkedHashSet::new));
// use allAll to add all the filtered Object to the second collection
mySecondCollection.addAll(filterdCollection);
// use removeAll to remove all the filtered Object from the first collection
myFirstCollection.removeAll(filterdCollection);
关于java - 如何根据谓词有效地将对象从一个 Java 集合传输到另一个集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52295058/