How to skip specific array index when using IntStream.filter in Java 8

I am learning and new to the Java 8 Stream API,

I wanted to write a program to search for even numbers in integer arrays with IntStream, so I came up with this solution,

int[] numbers = {1,2,3,4,5,6,7,8,9,10};

IntStream.of(numbers).filter(i -> i%2 == 0).forEach(System.out::println);

and it works right for me.

but how can I change filterto skip specific array indices from validation numbers?

eg,

if I want to skip numbers[1]from checking, if it is or not, then what should I do?

because iin the filter these are the values ​​of the elements of the array, not their indices.

can this be done?

+4
source share
3 answers

:

int[] numbers = ...;
IntStream.range(0, numbers.length).filter(i -> i!=1)
    .map(i -> numbers[i]).forEach(System.out::println);

, - , .

, , , - :

class IndexedValue {
    private int index, value;
    IndexedValue(int index, int value) {
        this.index = index ;
        this.value = value ;
    }
    int getIndex() { return index ;}
    int getValue() { return value ;}
}

int[] numbers = ... ;
IntStream.range(0, numbers.length).map(i -> new IndexedValue(i, numbers[i]))
    .filter(v -> v.getIndex() == 1 || v.getValue() % 2 == 0)
    .forEach(System.out::println);
+8

@James_D.

, , IndexedValue, - .

, :

int[] numbers = ... ;
IntStream.range(0, numbers.length)
  // an anonymous class is defined at this juncture
  // for the sake of discussion, said class is named
  // Whatever (FF8 reference).
  .mapToObj(i -> new Object() {
    final int index = i;
    final int value = numbers[i];
  })
  // IntStream translated to Stream<Whatever>
  .filter(v -> v.index != 1)
  // Stream<Whatever> with non-1 indices
  .filter(v -> v.value % 2 == 0)
  // Stream<Whatever> with even values
  .mapToInt(v -> v.value)
  // Stream<Whatever> to IntStream
  .forEach(System.out::println)
;

: , . , , JavaC. (-, Eclipse , javac's. . [ FF8])

+3

As an alternative solution, you can achieve the same result using iterators.

I am the author of Enumerables , which wraps iterable collections with functionality familiar to Stream. It provides a filtering method that has an index parameter.

    int[] numbers = {1,2,3,4,5,6,7,8,9,10};
    IntStream stream = IntStream.of(numbers);

    Enumerable<Integer> enumerable = new Enumerable(() -> stream.iterator());
    Enumerable<Integer> evens = enumerable.filter((x, i) -> x % 2 == 0 && i != 1);

    return evens.toList().stream();
+2
source

All Articles