Return List<Integer> from Method in Java 8?

  • A+
Category:Languages

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] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: