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.

4
  • I'd read up on vector addition firstly: physicsclassroom.com/class/vectors/u3l1b.cfm Commented Feb 6, 2013 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?. Commented Feb 6, 2013 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?!) Commented Feb 6, 2013 at 20:02
  • Possible duplicate of How to zip two Java Lists Commented Jan 25, 2018 at 4:32

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Why wouldn't just saying Va.addAll(Vb) in the first place be a good idea? Would that not work?
@BreadicalMD “It’s important to start with a new vector, otherwise you will change Va if you call Va.addAll().”
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.

3 Comments

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?
I think you are looking for something like a HashSet in that case.
Vector is still actual for such old but popular libraries as JSCH, for lsEntry class, for example.