Issue
I am new in Java Stream API and trying to solve some exercises. In a problem, I need to return the odd numbers as a List<Integer>
with the given range. First, I used a loop as shown below:
public static List<Integer> oddNumbers(int l, int r) {
List<Integer> list = new ArrayList<>();
for (int i = l; i <= r; i++) {
if (i % 2 != 0) {
list.add(i);
}
}
return list;
}
Then I thought that maybe it is better using stream in order to provide a cleaner solution. But it is not working when I tried with filter
and anyMatch
.
public static List<Integer> oddNumbers(int l, int r) {
return IntStream.range(l,r)
.filter(x -> x % 2 != 0)
// .anyMatch(x -> x % 2 == 0)
.collect(Collectors.toList());
}
So: 1. How can I make it work using stream?
2. Should I prefer the second approach as it seems to be cleaner?
Solution
- Like this:
public static List<Integer> oddNumbers(final int l, final int r) {
return IntStream.range(l, r + 1).filter(i -> i % 2 != 0).boxed().toList();
}
- It is a matter of taste, but one could argue that the intent is more clear using the stream API.
(toList()
is new from Java 16, otherwise one have to use collect(Collectors.toList())
Answered By - Andreas Berheim Brudin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.