【问题标题】:How to get MatchAllFilter to work properly and add other filters to MatchAllfilter?如何让 MatchAllFilter 正常工作并将其他过滤器添加到 MatchAllfilter?
【发布时间】:2019-01-07 00:50:30
【问题描述】:

我不认为我创建的 MatchAllFilter 类正在存储我尝试正确添加到其中的过滤器。当我传递一个列表时,没有一个过滤器正在工作。如何正确地将其他过滤器存储到 MatchAllFitlers 中,并将过滤器存储在 maf 中过滤我将要传递的列表?我已经一一测试了我所有的过滤器;我知道它们有效。

public class MatchAllFilter implements Filter {
 private ArrayList<Filter>filt;
 private String nameF;
 public MatchAllFilter(){
     filt= new ArrayList<Filter>();


    }
public void addFilter(Filter f){
    filt.add(f);


}

public boolean satisfies(QuakeEntry qe) { 
    for(Filter f:filt){
        if (f.satisfies(qe)){
            return true;

        }

    }
    return false;
} 

}

 public void testMatchAllFilter(){
    EarthQuakeParser parser = new EarthQuakeParser(); 
    //String source = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_week.atom";
    String source = "data/nov20quakedatasmall.atom";
    ArrayList<QuakeEntry> list  = parser.read(source);  
    MatchAllFilter maf=new MatchAllFilter();
    double depthMin=-100000.0;
    double depthMax=-10000.0;
    Filter f=  new DepthFilter(-100000.0,-10000.0);
    maf.addFilter(f);
    Filter e= new MagnitudeFilter(0.0, 2.0);
    maf.addFilter(e);
    Filter g= new PhraseFilter("any","a");
    maf.addFilter(g);

    //ArrayList<QuakeEntry>m10= filter(list,maf);       
    //for (QuakeEntry qe: list) { 
        //System.out.println(qe);
    System.out.println(maf);
    } 

【问题讨论】:

    标签: java list class filter filtering


    【解决方案1】:

    如果您要做的是检查filt 中的所有过滤器是否都适用于qe,那么问题是现在您正在检查any 的过滤器是否满足其标准,然后退出功能。换句话说,您正在检查 any 过滤器,而不是关闭 all 过滤器。例如:

    public boolean satisfies(QuakeEntry qe) { 
        for(Filter f : filt) {
            if (f.satisfies(qe)) { // one of the filters worked, let's exit
                return true;
            }
        }
        return false;
    }
    

    如果您需要检查是否所有过滤器都适用于qe,那么您必须遍历filt 中的整个过滤器列表

    public boolean satisfies(QuakeEntry qe) { 
        for(Filter f : filt){
            if (!f.satisfies(qe)) { // any of the filters criteria failed, then exit
                return false;
            }
        }
        return true; // the code will only reach this point if all the filters were applied
    } 
    

    如果你使用 Java 8+,你可以使用streams 例如

    public boolean satisfies(QuakeEntry qe) { 
        return filt.stream().allMatch(f -> f.satisfies(qe));
    } 
    

    【讨论】:

    • 我意识到我的测试中不需要 for 循环,因为过滤器已经有一个 for 循环。感谢您的帮助。
    • @Elizabeth 明白了。很高兴我能帮上忙!
    猜你喜欢
    • 2023-04-06
    • 2011-07-12
    • 1970-01-01
    • 2018-02-11
    • 2017-09-08
    • 2013-09-15
    • 2016-07-31
    • 2014-11-12
    相关资源
    最近更新 更多