OptionalInt (@NotNull List<? extends Component> components, int currentIndex, boolean next) { assert -1 <= currentIndex && currentIndex <= components.size(); int start = !next && currentIndex == -1 ? components.size() : currentIndex; return IntStream.range(0, components.size()) .map(i -> (next ? start + i + 1 : start + components.size() - i - 1) % components.size()) .filter(i -> components.get(i).isEnabled()) .findFirst(); }