Filter using For Each or Joins

I have a method to find the position of an 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 a single operator, i would like to pass a few different operators each time. I have appended the operator list onto an array. Is there a way to use the JOIN operator or For each syntax to loop through the list and find the position.

Answer

I am not sure why you would use JOIN of 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());
}

Leave a Reply

Your email address will not be published. Required fields are marked *