3

I have two list string different,

List<String> A= [1,2,3,4]; 
List<String> B= [1,2,5,6]; 

And I want to combine two list, in new list string in List C = new Arraylist ();

how to combine two list string , be like the example:

    C = [1,2,3,4,5,6];
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Samosir
  • 53
  • 1
  • 2
  • 7

8 Answers8

4

Use Collection.addAll(), and a TreeSet, to remove duplicates and keep the result sorted.

Set<String> c = new TreeSet<String>(a); //create a Set with all the elements in a
c.addAll(b); //add all the elements in b
Aleksander Blomskøld
  • 18,374
  • 9
  • 76
  • 82
3

This will get them combined

combined = new ArrayList<String>();
combined.addAll(A);
combined.addAll(B);

This will get the uniques

List<String> uniques = new ArrayList<String>(new HashSet<String>(combined));
maček
  • 76,434
  • 37
  • 167
  • 198
3

Do it like this :

listOne.removeAll(listTwo);
listTwo.addAll(listOne);
Collections.sort(listTwo);

You can remove the third line if you do not want it to be sorted.

Abhishek_Mishra
  • 4,551
  • 4
  • 25
  • 38
0

There are two ways to merge the results of both lists: using List#addAll or Set#addAll. The main difference between both is heavily explained here: What is the difference between Set and List?

Based on your request, you should merge both lists without repeating the items using a Set

List<String> lstA = new ArrayList<String>();
lstA.add("1");
lstA.add("2");
lstA.add("3");
lstA.add("4");
List<String> lstB = new ArrayList<String>();
lstA.add("1");
lstA.add("2");
lstA.add("5");
lstA.add("6");
Set<String> lstC = new LinkedHashSet<String>();
lstC.addAll(A);
lstC.addAll(B);
List<String> lstAB = new ArrayList(lstC);
Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
0

Declaration of A and B seems to be wrong.

However, given two lists A and B, to combine them into C, you can use the following code: C.addAll(A); C.addAll(B);

An Cong Tran
  • 350
  • 1
  • 8
0
List<String> A= new ArrayList<String>();
List<String> B= new ArrayList<String>();

Set<String> set = new TreeSet<String>(A);
set.addAll(B);
System.out.println(new ArrayList<String>(set));
Sandeep Pathak
  • 10,567
  • 8
  • 45
  • 57
0
  Set<String> set = new TreeSet<String>(A); // for keeping the output sorted else you can also use java.util.HashSet
  set.addAll(B);
  List<String> finalList = new ArrayList<String>(set);
Rahul
  • 15,979
  • 4
  • 42
  • 63
0

To get a List<String> in sorted order, use this piece of code

    String a[] = {"1","2","3","4"};
    String b[] = {"1","2","5","6"};
    List<String> A= Arrays.asList(a); 
    List<String> B= Arrays.asList(b); 

    Set<String> CTemp = new TreeSet<>();  
    CTemp.addAll(A);
    CTemp.addAll(B);

    List<String> C = new ArrayList<>(CTemp);
Kiran Mohan
  • 2,696
  • 6
  • 36
  • 62