java - 如何根据谓词有效地将对象从一个 Java 集合传输到另一个集合?

标签 java collections java-8 java-stream

首先,我希望以前没有人问过这个问题。我看了一点,找不到合适的答案: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::addAllCollection::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/

相关文章:

java - 持久类是否应该初始化实例变量集合

java-8 - 使用 LocalDateTime 的客户端 Resteasy

java - Solr 字符串字段搜索包含特殊字符

java - 在 Java 7 或更低版本中,HOWTO 使用在 map 中找到的键/值来过滤 map 对象列表

java - Spring中Json无法反序列化实例错误

c# - NHibernate 正在将我的收藏变成只读。我怎样才能阻止它?

Java 8 Stream - 过滤器和 foreach 方法未按预期打印

java-8 - 解析 LocalDateTime 格式

java NullPointerException 与 LocationManager

java - ServletContext 和 ServletActionContext 有什么区别