Adding two arraylists to one

I want to check branchList whether it has the same element or not, if the same branchList and tglList element add a separate arraylist and put this arraylist in another arraylist.

As a result, I want BranchList1 to have 2 arraylist, where the 1st arraylist contains the element '1' and the second arraylist contains the element '2', and TglList1 has 2 array elements, but what I get is the 1st , and the 2nd array, gets the same value.

How can I do that?

ArrayList branchList = new ArrayList(); branchList.add("1"); branchList.add("1"); branchList.add("1"); branchList.add("2"); branchList.add("2"); branchList.add("2"); ArrayList tglList = new ArrayList(); tglList.add("5"); tglList.add("10"); tglList.add("20"); tglList.add("100"); tglList.add("500"); tglList.add("1000"); ArrayList newBranchList = new ArrayList(); ArrayList newTglList = new ArrayList(); ArrayList BranchList1 = new ArrayList(); ArrayList TglList1 = new ArrayList(); ArrayList abc = new ArrayList(); String checkBranch = new String(); for(int i=0;i<branchList.size();i++){ String branch = branchList.get(i).toString(); if(i==0 || checkBranch.equals(branch)){ newBranchList.add(branch); newTglList.add(tglList.get(i).toString()); }else{ BranchList1.add(newBranchList); TglList1.add(newTglList); newBranchList.clear(); newTglList.clear(); newBranchList.add(branch); newTglList.add(tglList.get(i).toString()); } if(i==(branchList.size()-1)){ BranchList1.add(newBranchList); TglList1.add(newTglList); } checkBranch = branch; } } 

The expected result is as follows:

 BranchList1 = [ [1,1,1],[2,2,2]] TglList1 = [[5,10,20],[50,100,200]] 

but i get

 BranchList1 = [ [2,2,2],[2,2,2]] TglList1 = [[50,100,200],[50,100,200]] 

How can I change the code

+8
java arraylist
source share
1 answer

I have not completely read your code (and I do not quite understand what you are asking), but if you want to combine (add elements) branchList and tglList in TglList1 , try the following:

 TglList1.addAll(branchList); TglList1.addAll(tglList); 

After that, TglList1 should contain all the elements of both lists. If you need a sort list, you can call Collections.sort(TglList1) after that (just note that sort lines can put “100” to “2”, because “1” is lexically less than “2”).

+26
source share

All Articles