Search code examples
java-stream

Java stream filter with element in a constant tab


I have two class like this :

public class Forecast {
    private List<Element> elements;
    private Person person;
}
public class Element {
    private String element;
}

I have a constant of String[] like this : private static final String[] ELE = {"element1", "element2", "element3"};

I would like to retrieve all the elements of my list in forecast which contains one of the elements of my constant with Stream.

So, I started by doing this to test :

public List<Element> getElement(String person) {
    return getElement(person).getList()
            .stream()
            .filter(r  -> r.get(0).getElement.equals("element1"))
            .collect(Collectors.toList());
}

Now I would like to use my constant ELE, and I don't find how to go through it and test my elements

Thanks


Solution

  • private static final List<String> ELE_LIST = java.util.Arrays.asList(ELE);
    
    public List<Element> getElement(String person) {
        return getElement(person).getList()
                .stream()
                .filter(r -> ELE_LIST.contains(r.get(0).getElement()))
                .collect(Collectors.toList());
    }