Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java merge 2 collections in O(1)

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.

like image 314
Tiddo Avatar asked Dec 03 '11 13:12

Tiddo


People also ask

How do you add two collections in Java?

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.

How do I combine Iterables?

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.

How do I combine two streams in Java?

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.

How do I merge Hashsets?

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).


1 Answers

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.

like image 182
ColinD Avatar answered Sep 23 '22 12:09

ColinD