I have a list that contains computed values and I can not change or transform the list to e.g. Map. I need to iterate through this list and get all the odd/even items. To do this with the old fashion Java for loop
is quite easy.
Let's say that I have this list:
var results = Arrays.asList("1", "2", "3", "4", "5", "6");
Get all odd items:
for (int i = 0; i < results.size(); i = 2) {
var current = results.get(i);
process(current);
}
Get all even items:
for (int i = 1; i < results.size(); i = 2) {
var current = results.get(i);
process(current);
}
Can I get somehow the same result with lambda forEach()
easily in one line?
>UPDATE<
Sorry for this, but I forgot to mention that the values actually are not numbers like 1, 2, 3, etc. I just used these values as an example. The solution must not rely on the value of the items.
CodePudding user response:
An alternative could be to use Stream.iterate
IntStream.iterate(0, i -> i < results.size(), i -> i 2)
.mapToObj(i -> results.get(i))
.forEach(this::process);
IntStream.iterate(1, i -> i < results.size(), i -> i 2)
.mapToObj(i -> results.get(i))
.forEach(this::process);
Use YourClass::process
if process
a static method.
CodePudding user response:
Based on your update to the question
You could do something like this:
// even elements
IntStream.range(0, results.size())
.filter(i -> i % 2 == 0)
.mapToObj(results::get)
.forEach(this::process);
// odd elements
IntStream.range(0, results.size())
.filter(i -> i % 2 != 0)
.mapToObj(results::get)
.forEach(this::process);