I have the following method (see below). The code is working but I got сomments that there is a lot of repeating and that I should use IntStream.
Could you specify how to better optimize the code? Thanks in advance.
public static List<Integer> oddOrEven(List<Integer> integers) {
long sum = integers.stream().mapToInt(i ->i).summaryStatistics().getSum();
if (sum % 2 == 0) {
return integers.stream().filter(x -> x % 2==0).distinct().collect(Collectors.toList());
} else if (sum % 2 != 0) {
return integers.stream().filter(x -> x % 2 != 0).distinct().collect(Collectors.toList());
}
return null;
}
It looks like you only need the sum of the elements in order to check if it's odd or even. To know that, it's enough to check if the number of odd elements is odd or even.
You can split the input into odd and even lists, and decide which one to return based on the size of the odd List:
public static List<Integer> oddOrEven(List<Integer> integers) {
Map<Boolean,List<Integer>>
oddsAndEvens = integers.stream()
.collect(Collectors.partitioningBy(i->i%2==0));
return oddsAndEvens.get(false).size() % 2 == 0 ? // check if there's an even number of odd
// elements, which means the sum is even
oddsAndEvens.get(true) : // return the even elements
oddsAndEvens.get(false); // return the odd elements
}
Testing:
System.out.println (oddOrEven(Arrays.asList (1,2,3,4,5)));
System.out.println (oddOrEven(Arrays.asList (1,2,3,4,5,3)));
Output:
[1, 3, 5]
[2, 4]
EDIT:
In my original answer I missed the distinct() step, which should be performed after we decide whether to return the odd or even elements. I'm afraid this requires adding a second Stream pipeline:
public static List<Integer> oddOrEven(List<Integer> integers) {
Map<Boolean,List<Integer>>
oddsAndEvens = integers.stream()
.collect(Collectors.partitioningBy(i->i%2==0));
return oddsAndEvens.get(false).size() % 2 == 0 ?
oddsAndEvens.get(true).stream().distinct().collect(Collectors.toList()) :
oddsAndEvens.get(false).stream().distinct().collect(Collectors.toList());
}
or (with Holger's suggestion):
public static List<Integer> oddOrEven(List<Integer> integers) {
Map<Boolean,List<Integer>>
oddsAndEvens = integers.stream()
.collect(Collectors.partitioningBy(i->i%2==0));
return oddsAndEvens.get(oddsAndEvens.get(false).size() % 2 == 0)
.stream()
.distinct()
.collect(Collectors.toList());
}
long sum = integers.stream().reduce(0, (u, v) -> u + v);
return integers.stream().filter(x -> (x % 2)==(sum % 2)).distinct().collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With