4

Is there any easy and quick way to merge 2 java vectors to 1?

For example if I have:

  Vector<Object> Va = (Vector<Object>)Return_Vector_with_Objs();
  Vector<Object> Vb = (Vector<Object>)Return_Vector_with_Objs();

  Vector<Object> Vmerge_a_b = function_that_takes_a_b_merges(Va,Vb);

Is there any function like function_that_takes_a_b_merges or easy way to merge these 2 vectors ?

I don't want to do it with loops and add() etc. I am asking if there is a quicker way.

EDIT: I also want the repeated objects to be ruled out.

  • I'd read up on vector addition firstly: http://www.physicsclassroom.com/class/vectors/u3l1b.cfm –  Feb 06 '13 at 19:55
  • 2
    Depends on your definition of _merging_. You can use `Vector#addAll`, a `TreeSet` if you want orderer unrepeated elements, an `ArrayList` or even a `LinkedList`. What's merging for you? the elements of vector1 followed by the elements of vector2?. – Fritz Feb 06 '13 at 19:57
  • That is a good comment. I actually want a new vector with all the unrepeated objects. I don't care about ordering at all (but just for curiosity how could it be ordered?!) –  Feb 06 '13 at 20:02
  • Possible duplicate of [How to zip two Java Lists](https://stackoverflow.com/questions/31963297/how-to-zip-two-java-lists) – tkruse Jan 25 '18 at 04:32

2 Answers2

6

Sure!

static Vector<Object> function_that_takes_a_b_merges(Vector<Object> Va, Vector<Object> Vb) {
  Vector<Object> merge = new Vector<Object>();
  merge.addAll(Va);
  merge.addAll(Vb);
  return merge;
}

It’s important to start with a new vector, otherwise you will change Va if you call Va.addAll().

andrewdotn
  • 32,721
  • 10
  • 101
  • 130
3

You could do:

Set<String> set = new HashSet<>(va);
set.addAll(vb);
Vector<String> merged = new Vector<>(set);

Note:Vector is quite an old Collection now which has the overhead of synchronized methods which has a performance cost. ArrayList could be used instead and also has the addAll method from the List interface contract. If you do require a synchronized Collection, you can use Collections.synchronizedList to synchronize your original List.

Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • 1
    I actually wanted to have a synchronized collection that's why I used it. So there will be repeated object in mergedVector with this method? –  Feb 06 '13 at 20:03
  • I think you are looking for something like a `HashSet` in that case. – Reimeus Feb 06 '13 at 20:11
  • Vector is still actual for such old but popular libraries as JSCH, for lsEntry class, for example. – Zon Oct 31 '13 at 17:03