0

I have such class:

public class FirstTypeMD extends BaseParams {
    Integer framePerSec;

    public FirstTypeMD(Integer energyCons, Integer mass, Integer tempRange, Boolean electricProtect,
            Boolean radioProtect, Integer framePerSec) {
        super(energyCons, mass, tempRange, electricProtect, radioProtect);

        this.framePerSec = framePerSec;
    }


    public void setFramePerSec(Integer framePerSec) {
        this.framePerSec = framePerSec;
    }

    public Integer getFramePerSec() {
        return framePerSec;
    }

}

I would like to create dynamic filter for arraylist with this class objects. For example at certain situation I will need result of filtering by energyCons in another by tempRange and somtimes both of them. I need filter with a lot of variations of this class fields. I also asked such question but here I was suggested to create a lot of constructors for filtering. For me it looks strange :(

1 Answer 1

0

So, I have created very simple way of arraylist filtering. I used HashMap with predicates:

HashMap<Integer, Predicate<FirstTypeMD>> filter_1 = new HashMap<>();

to which I can add some filters:

switch (p1.getSelectionIndex()) {
case 1: {
sg.filter_1.put(0, model -> model.framePerSec <= 5);
break;
}
case 2: {
sg.filter_1.put(0, model -> model.framePerSec >= 5 & model.framePerSec <= 100);
break;
}
case 3: {
sg.filter_1.put(0, model -> model.framePerSec >= 100);
break;
}
default: {
sg.filter_1.remove(0);
break;
}
}

and then finally I can use this hashmap:

public ArrayList<FirstTypeMD> filterT1() {
        return filter_1.containsKey(0)
                ? new ArrayList<FirstTypeMD>(
                        fTypeArrayList.stream().filter(filter_1.values().stream().reduce(x -> true, Predicate::and))
                                .collect(Collectors.toList()))
                : fTypeArrayList;
    }

and loop over this new array:

for (FirstTypeMD fModeMd : sg.filterT1()) {
                        
}

Maybe my solution isn't so good, but it solved my problem :) Maybe it will be useful for someone else.

P.S. You can also write your suggestions in comments :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.