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]; 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]; 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 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.
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); 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)); TreeSet maintains the data sorted, not ordered. LinkedHashSet maintains the data ordered but not sorted.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);