Given a list of integers, separate odd and even numbers
Categories: Java 8(JDK1.8) Java Java Examples
package r4r.co.in;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class SeparateOddAndEvenNumbers {
public static void main(String[] args) {
//Given a list of integers, separate odd and even numbers.
Integer[] input= {1,2,3,4,5,6,7,8,9,10};
Map<Boolean, List<Integer>> dmap=Stream.of(input).collect(Collectors.partitioningBy(s->s%2==0));
for (Map.Entry<Boolean,List<Integer>> entry:dmap.entrySet()) {
List<Integer> values=entry.getValue();
Boolean key=entry.getKey();
if(key)
System.out.println("Even");
else
System.out.println("Odd");
System.out.println(values);
}
}
}
Output:-
Odd
[1, 3, 5, 7, 9]
Even
[2, 4, 6, 8, 10]