Сумма четных элементов массива через стрим
Создал массив array . Хочу сложить только четные индексы массива ( элементы четных индексов)
int sum = Arrays.stream(array).filter(i -> i % 2 == 0) - фильтр фильтрует только само содержание индексов, но не по самим индексам. Подскажите как сделать правильное условие.
Ответы (1 шт):
int[] array = { 5, -999, 6, -999, 7, -999, 7};
int sum = IntStream.range(0, array.length)
.filter(index -> index % 2 == 0)
.map(index -> array[index])
.sum();
System.out.println(sum);
Console:
25
Это помогло мне решить Вашу проблему: Stackoverflow: Как я могу получить индекс элемента внутри потоков java
range(...)
static IntStream range(int startInclusive, int endExclusive)
Returns a sequential ordered IntStream from startInclusive(inclusive) to endExclusive (exclusive) by an incremental step of 1. API Note: An equivalent sequence of increasing values can be producedsequentially using a for loop as follows:
for (int i = startInclusive; i < endExclusive ; i++) { ... }
Parameters:
startInclusive - the (inclusive) initial valueendExclusive - the exclusive upper bound
Returns:
a sequential IntStream for the range of intelements