Filter used for each or join

I have a way to find the position of the operator.

public Optional<Integer> findToken(Character operator) {
    return tokenList.stream()
            .filter(x -> {
                return x.position >= startPosition &&
                        x.position <= endPosition &&
                        x.operator == operator;
            })
            .findFirst()
            .map(t -> t.position);
}

      

Instead of passing one operator, I would like to pass several different operators each time. I added a list of operators to an array. Is there a way to use the JOIN statement or for each syntax to loop through the list and find the position.

+3


source to share


1 answer


I'm not sure why you are using JOIN forEach (), but here is a solution using Set.contains ():



public List<Integer> findTokens(Character operators[]) {
    Set<Character> set = new HashSet<>();
    set.addAll(Arrays.asList(operators));
    return tokenList.stream()
        .filter(x -> {
            return x.position >= startPosition &&
                    x.position <= endPosition &&
                    set.contains(x.operator);
        })
        .map(t -> t.position)
        .collect(Collectors.toList());
}

      

+2


source







All Articles