I am studying Java8 and want to perform following operations using stream API in Java8.
Input: List of (1,2,3,4,5,6,7,8,9)
Output: Odd List - (1,3,5,7,9) Even List - (2,4,6,8)
I can do this operation in single for loop in traditional java like
List<Integer> ints = Arrays.asList(3,4,2,5,6,7,4,5);
List<Integer> oddList = new ArrayList<>();
List<Integer> evenList = new ArrayList<>();
for (Integer i : ints) {
if (i % 2 == 0) {
evenList.add(i);
} else {
oddList.add(i);
}
}
I know a way to do this in Java8 style as follows -
List<Integer> evens = ints.stream().filter(i -> i % 2 == 0).collect(Collectors.toList());
List<Integer> odds = ints.stream().filter(i -> i % 2 == 1).collect(Collectors.toList());
But here the problem is that I am iterating the ints twice instead of once. Is there a way that this can be done without iterating twice in streams?