Concatenate vectors in Java

Is there a simple and quick way to combine 2 java vectors into 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 an easy way to combine these 2 vectors?

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

EDIT: I also want duplicate objects to be excluded.

+3


source to share


2 answers


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

.

+5


source


You can do:

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

      



Note. Vector

is now quite old Collection

, which has the overhead of synchronized methods that have execution cost. ArrayList

can be used instead and also has a method addAll

from an interface contract List

. If you require a synchronized one Collection

, you can use Collections.synchronizedList to synchronize the original List

.

+2


source







All Articles