简体   繁体   中英

How to filter Collection in order to get two Lists of different types

I have following problem:

I want to validate my data based on some conditions, my data is a collection List<ClassA> While validating I want to filter my List<ClassA> so that eventually I get List<ClassA> which consist of only valid data and List<ClassB> which consist of invalid data.

I currently have only two ideas on how to do it but I like neither of them.

  1. I create ClassC that has List<ClassA> and List<ClassB> that I return with validate method of my Validator class

     List<ClassC> validate(List<ClassA>) 

    The problem of this appraoch is that, ClassA is request object and ClassB is response Object so putting them into on Class looks sort of strange.

  2. My Validator class hava valid method but does not return anything. Instead it has two other methods, getValidData and getInvalidData which return List<ClassA> and List<ClassB> accordingly that are created with validate method run

     void validate(List<ClassA>) List<ClassA> getValidData() List<ClassB> getInvalidData() 

    I like that one better but I am still not happy as methods needs run in sequence.

Any idea how to deal with such problem better?

If you always need to validate the list, you could do it beforehand and only expose the getValid and getInvalid methods:

public class Validator {

    private final List<A> all;
    private final List<A> invalid = new ArrayList<>();
    private final List<A> valid = new ArrayList<>();

    public Validator(List<A> all) {
        this.all = new ArrayList<> (all);
        validate(all); 
    }
    private void validate(List<A> all) {
        //populate invalid and valid
    }
    public List<A> getInvalid() { return invalid; }
    public List<A> getValid() { return valid; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM