【问题标题】:return new instance of filtered elements返回过滤元素的新实例
【发布时间】:2019-09-29 18:57:10
【问题描述】:

我的界面InterA:

public interface InterA
{
     boolean check(Record line);
}

我的检查方法:

public class ClassA implements InterA{

    @Override
    public boolean check(Record line) {
        if (condition) {
            return true;
        } else {
            return false;
        }
    }
}

如何在下面的过滤器方法中返回一个新的 ClassB 实例,该实例仅包含过滤后的元素? 提前谢谢你。

public class ClassB {

List<Record> list;

public ClassB(List<Record> list) {
        this.list = list;
    }

public ClassB filter(InterA a) {


    }

【问题讨论】:

  • ArrayList filter的可能重复
  • 在过滤方法内部,迭代列表 或类似for(Record record: list) 然后在for循环内部,使用a.check(record)。如果为真,则返回 ClassB 的新实例。

标签: java


【解决方案1】:

使用Stream.filter() 过滤匹配criteriaRecords。然后将过滤后的元素收集到一个列表中(Stream.collect()),并创建一个ClassB 的实例,将列表传递给构造函数。

public ClassB filter(InterA a) {
    return new ClassB(
        this.list
        .stream()
        .filter(a::check)
        .collect(Collectors.toList())
    );
}

【讨论】:

  • 这个建议需要解释一下它的作用和工作原理。
猜你喜欢
  • 1970-01-01
  • 2011-03-29
  • 2018-06-28
  • 2017-05-13
  • 2018-08-21
  • 2012-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多