Henok Tesfaye
Henok Tesfaye

Reputation: 9570

Best design pattern for selecting a group with in a list with the value of the condition may vary?

public class Swimmers extends SwimmersPrototype{
    List<Swimmer> swimmers;
    SortStrategy sortStrategy;

    public Swimmers() {
        swimmers = new ArrayList();
    }

    @Override
    public SwimmersPrototype clone() throws CloneNotSupportedException{
        Swimmers swp = (Swimmers)super.clone();
        return swp;
    }

    public void setSortStrategyAndSort(SortStrategy s) {
        setSortStrategy(s);
        sort();
    }

    public void setSortStrategy(SortStrategy s){
        sortStrategy = s;
    }

    public void addSwimmer(Swimmer s){
        swimmers.add(s);
    }

    public List<Swimmer> sort() {
        return (swimmers = sortStrategy.sort(new ArrayList<>(swimmers)));
    }

    public List<Swimmer> getSwimmers() {
        return swimmers;
    }
}

I've Swimmers class to act as an in-memory database of Swimmer records. I've three tables one to show list of swimmer, second one to list swimmers with only age between 18-25, and the last one to list swimmers with only age 26-35.

Swimmer class have an age property, but the age of a Swimmer may change and may result in another age group, like if John is 25 and celebrate his birthday while in the game, he must be in the second group.

So here which design pattern is best to select a group based on some condition in a list, also the value of the condition may vary so it results change in a group?

Upvotes: 1

Views: 249

Answers (1)

Ruslan
Ruslan

Reputation: 6300

Create a Predicate for each case you need:

Predicate<Integer> youngSwimmer = integer -> integer > 18 && integer < 25;
Predicate<Integer> oldSwimmer = integer -> integer > 26 && integer < 35;

Then test it like this:

List<Swimmer> = getSwimmers().stream()
    .filter(swimmer -> youngSwimmer.test(swimmer.getAge()))
    .collect(Collectors.toList())

You can define a separate mehtod for this and pass any predicate you need to get list of Swimmers of specific age

Upvotes: 3

Related Questions