I want to merge down 3 arraylist in one in java. Does anyone know which is the best way to do such a thing?
Approach: ArrayLists can be joined in Java with the help of Collection. addAll() method. This method is called by the destination ArrayList and the other ArrayList is passed as the parameter to this method. This method appends the second ArrayList to the end of the first ArrayList.
You can compare two array lists using the equals() method of the ArrayList class, this method accepts a list object as a parameter, compares it with the current object, in case of the match it returns true and if not it returns false.
Use ArrayList.addAll()
. Something like this should work (assuming lists contain String
objects; you should change accordingly).
List<String> combined = new ArrayList<String>(); combined.addAll(firstArrayList); combined.addAll(secondArrayList); combined.addAll(thirdArrayList);
I can see by your comments that you may actually be trying to create a 2D list. If so, code such as the following should work:
List<List<String>> combined2d = new ArrayList<List<String>>(); combined2d.add(firstArrayList); combined2d.add(secondArrayList); combined2d.add(thirdArrayList);
What about using java.util.Arrays.asList to simplify merging?
List<String> one = Arrays.asList("one","two","three"); List<String> two = Arrays.asList("four","five","six"); List<String> three = Arrays.asList("seven","eight","nine"); List<List<String>> merged = Arrays.asList(one, two, three);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With