2

I'm newbie in Reactive. Using JDK 1.8, how can I convert these imperative code into Reactive style.

List<int> evenArr, oddArr, arr;
// pretending 'arr' have some values, 'evenArr' & 'oddArr' have already init
for (int n : arr) {
    if (n%2) evenArr.add(n);
    else oddArr.add(n);
}

Now I have only idea that search 'arr' twice, like:

arr.stream().filter(n -> n%2).foreach(evenArr::add);
arr.stream().filter(n -> n%2!=0).foreach(oddArr::add);

Are there another ways? Searching 'arr' twice is expensive.

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
Hai
  • 37
  • 6

2 Answers2

5

You should use Collectors.partitioningBy like this.

List<Integer> arr = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
Map<Boolean, List<Integer>> result = arr.stream()
    .collect(Collectors.partitioningBy(i -> i % 2 == 0));
List<Integer> evenArr = result.get(true);
List<Integer> oddArr = result.get(false);
System.out.println("evenArr=" + evenArr);
System.out.println("oddArr=" + oddArr);

result

evenArr=[0, 2, 4, 6, 8]
oddArr=[1, 3, 5, 7, 9]
4

You should read more about what Reactive programming is because you misunderstood the concept. Anyway, you could do the even/odd thing with Collectors.groupingBy, in case you don't want to search the array twice

 Map<Boolean, List<Integer>> collect = arr.stream()
                 .collect(Collectors.groupingBy(o -> o % 2 == 0));
Schidu Luca
  • 3,897
  • 1
  • 12
  • 27
  • Yeah ur right. Ofc I know that searching twice was wrong, but I have no idea to write it correctly. – Hai Jul 31 '17 at 09:43