MergerBiFunction implements BiFunction<List<T>, List<T>, List<T>> { @Override public List<T> apply(List<T> a, List<T> b) throws Exception { int n = a.size() + b.size(); if (n == 0) { return new ArrayList<T>(); } List<T> both = new ArrayList<T>(n); Iterator<T> at = a.iterator(); Iterator<T> bt = b.iterator(); T s1 = at.hasNext() ? at.next() : null; T s2 = bt.hasNext() ? bt.next() : null; while (s1 != null && s2 != null) { if (comparator.compare(s1, s2) < 0) { both.add(s1); s1 = at.hasNext() ? at.next() : null; } else { both.add(s2); s2 = bt.hasNext() ? bt.next() : null; } } if (s1 != null) { both.add(s1); while (at.hasNext()) { both.add(at.next()); } } else { both.add(s2); while (bt.hasNext()) { both.add(bt.next()); } } return both; } MergerBiFunction(Comparator<? super T> comparator); @Override List<T> apply(List<T> a, List<T> b);  }
@Test public void firstEmpty() throws Exception { MergerBiFunction<Integer> merger = new MergerBiFunction<Integer>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1.compareTo(o2); } }); List<Integer> list = merger.apply(Collections.<Integer>emptyList(), Arrays.asList(3, 5)); assertEquals(Arrays.asList(3, 5), list); }
@Test public void bothEmpty() throws Exception { MergerBiFunction<Integer> merger = new MergerBiFunction<Integer>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1.compareTo(o2); } }); List<Integer> list = merger.apply(Collections.<Integer>emptyList(), Collections.<Integer>emptyList()); assertEquals(Collections.<Integer>emptyList(), list); }
@Test public void secondEmpty() throws Exception { MergerBiFunction<Integer> merger = new MergerBiFunction<Integer>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1.compareTo(o2); } }); List<Integer> list = merger.apply(Arrays.asList(2, 4), Collections.<Integer>emptyList()); assertEquals(Arrays.asList(2, 4), list); }
@Test public void sameSize() throws Exception { MergerBiFunction<Integer> merger = new MergerBiFunction<Integer>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1.compareTo(o2); } }); List<Integer> list = merger.apply(Arrays.asList(2, 4), Arrays.asList(3, 5)); assertEquals(Arrays.asList(2, 3, 4, 5), list); }
@Test public void sameSizeReverse() throws Exception { MergerBiFunction<Integer> merger = new MergerBiFunction<Integer>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1.compareTo(o2); } }); List<Integer> list = merger.apply(Arrays.asList(3, 5), Arrays.asList(2, 4)); assertEquals(Arrays.asList(2, 3, 4, 5), list); }