Reputation: 55
How can I filter elements of the list based on their index(position) using stream() in Java?
I want to filter every third element (i.e. indices 0, 3, 6, 9,... of a List<String>
).
Upvotes: 0
Views: 1522
Reputation: 11050
Since Java 9 you can use IntStream.iterate()
to achieve that:
IntStream.iterate(0, i -> i < list.size(), i -> i + 3)
.mapToObj(list::get)
.forEach(System.out::println);
If you are using Java 8 you can use this:
IntStream.iterate(0, i -> i + 3)
.limit(list.size() / 3)
.mapToObj(list::get)
.forEach(System.out::println);
Edit: As Holger pointed out in the comments a more efficient solution would be this:
IntStream.range(0, list.size() / 3)
.mapToObj(i -> list.get(i * 3))
.forEach(System.out::println);
Upvotes: 3
Reputation: 394156
You'll have to use an IntStream.
For example, the following will create a Stream
containing all the List
elements whose indices are divisible by 3:
List<String> yourList = ...
IntStream.range(0,yourList.size()) // IntStream of 0,1,2,3,...
.filter(i -> i % 3 == 0) // IntStream of 0,3,6,...
.mapToObj(yourList::get) // Stream<String> of yourList.get(0),yourList.get(3),...
...
Upvotes: 2