I need to be able to merge 2 large collections into 1. Which collection type can I use best? I don't need random access to the individual elements. Usually I'd go for a linkedlist, however I can't merge 2 linkedlist in Java with a runtime of O(1), which could be done in many other languages, since I'll have to copy each element to the new list.
Edit: Thank you for all your answers. Your answers were all very helpful, and I managed to get the job done. Next time I will use my own implementation of a linked list to begin with.
Using the concat() Method. The static method concat() combines two Streams logically by creating a lazily concatenated Stream whose elements are all the elements of the first Stream followed by all the elements of the second Stream.
Concatenate Iterables using concat Method The Iterables class provides concat method that accepts n number of Iterable instances and returns a new Iterable instance having all elements concatenated. Note that this method creates a new instance; hence we can pass Immutable Lists.
concat() in Java. Stream. concat() method creates a concatenated stream in which the elements are all the elements of the first stream followed by all the elements of the second stream. The resulting stream is ordered if both of the input streams are ordered, and parallel if either of the input streams is parallel.
The shortest and most idiomatic way to merge contents of a HashSet<T> object with contents of another HashSet<T> is using the HashSet<T>. UnionWith() method. It modifies the HashSet<T> to contain all elements that are present in itself along with elements in the specified HashSet (or any other IEnumerable in general).
You can create a concatenated Iterable
view in O(1) using one of Guava's Iterables.concat methods:
Iterable<T> combined = Iterables.concat(list1, list2);
This will allow you to iterate over all the elements of both lists as one object without copying any elements.
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