| 1 |
/* |
| 2 |
* Copyright (c) 2016-present, RxJava Contributors. |
| 3 |
* |
| 4 |
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in |
| 5 |
* compliance with the License. You may obtain a copy of the License at |
| 6 |
* |
| 7 |
* http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
* |
| 9 |
* Unless required by applicable law or agreed to in writing, software distributed under the License is |
| 10 |
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See |
| 11 |
* the License for the specific language governing permissions and limitations under the License. |
| 12 |
*/ |
| 13 |
|
| 14 |
package io.reactivex.rxjava3.internal.util; |
| 15 |
|
| 16 |
import java.util.*; |
| 17 |
|
| 18 |
import io.reactivex.rxjava3.functions.BiFunction; |
| 19 |
|
| 20 |
/** |
| 21 |
* A BiFunction that merges two Lists into a new list. |
| 22 |
* @param <T> the value type |
| 23 |
*/ |
| 24 |
public final class MergerBiFunction<T> implements BiFunction<List<T>, List<T>, List<T>> { |
| 25 |
|
| 26 |
final Comparator<? super T> comparator; |
| 27 |
|
| 28 |
public MergerBiFunction(Comparator<? super T> comparator) { |
| 29 |
this.comparator = comparator; |
| 30 |
} |
| 31 |
|
| 32 |
@Override |
| 33 |
public List<T> apply(List<T> a, List<T> b) { |
| 34 |
int n = a.size() + b.size(); |
| 35 |
if (n == 0) { |
| 36 |
return new ArrayList<>(); |
| 37 |
} |
| 38 |
List<T> both = new ArrayList<>(n); |
| 39 |
|
| 40 |
Iterator<T> at = a.iterator(); |
| 41 |
Iterator<T> bt = b.iterator(); |
| 42 |
|
| 43 |
T s1 = at.hasNext() ? at.next() : null; |
| 44 |
T s2 = bt.hasNext() ? bt.next() : null; |
| 45 |
|
| 46 |
while (s1 != null && s2 != null) { |
| 47 |
if (comparator.compare(s1, s2) < 0) { // s1 comes before s2 |
| 48 |
both.add(s1); |
| 49 |
s1 = at.hasNext() ? at.next() : null; |
| 50 |
} else { |
| 51 |
both.add(s2); |
| 52 |
s2 = bt.hasNext() ? bt.next() : null; |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
if (s1 != null) { |
| 57 |
both.add(s1); |
| 58 |
while (at.hasNext()) { |
| 59 |
both.add(at.next()); |
| 60 |
} |
| 61 |
} else { |
| 62 |
both.add(s2); |
| 63 |
while (bt.hasNext()) { |
| 64 |
both.add(bt.next()); |
| 65 |
} |
| 66 |
} |
| 67 |
|
| 68 |
return both; |
| 69 |
} |
| 70 |
} |