Am trying to merge a couple of lists into one, eliminating the duplicates. mergeSorted method in Guava seems to apply to my case. But when I do try it, i see to get a compilation error about the arguments that I pass to the method. My code is as simple as this, I have two lists, concat them into one and then try to mergeSort it, but I get a compilation error on line four.
final List<Integer> first = Lists.newArrayList(1, 2, 3);
final List<Integer> second = Lists.newArrayList(4, 2, 5, 6);
Iterable<Integer> some = Iterables.concat(first, second);
final Iterable all = Iterables.<Integer>mergeSorted(some, comp);
System.out.println(all);
It looks like it is mergeSorted is expecting Iterable<? extends Iterable<? extends T>> iterables but the method description seems to suggest that input can be the merged contents of all given iterables
@Beta public static <T> Iterable<T> mergeSorted(Iterable<? extends Iterable<? extends T>> iterables, Comparator<? super T> comparator)
Returns an iterable over the merged contents of all given iterables. Equivalent entries will not be de-duplicated.
Callers must ensure that the source iterables are in non-descending order as this method does not sort its input.
You're currently concatenating your iterables together before merging - at that point, the result isn't sorted any more, apart from anything else!
As you've noted, mergeSorted needs an "iterable of iterables". Full sample:
import java.util.List;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
public class Test {
public static void main(String[] args) {
List<Integer> first = Lists.newArrayList(1, 2, 3);
// Note that each input list has to be sorted already!
List<Integer> second = Lists.newArrayList(2, 4, 5, 6);
Iterable<Integer> all = Iterables.mergeSorted(
ImmutableList.of(first, second), Ordering.natural());
System.out.println(Joiner.on(", ").join(all));
}
}
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