KaiquanMah's picture
newList.addAll(list1); Collections.sort(newList)
c0b7c5c verified
raw
history blame
2.99 kB
Write the method
ArrayList<Integer> combine(ArrayList<Integer> list1, ArrayList<Integer> list2)
which takes as parameters two lists of integers.
The lists are ordered in ascending order (i.e. the smallest number is first and the largest last).
The method returns a new list of integer type with all the elements of the parameter lists combined.
In the new list, the elements are also ordered in order of magnitude.
Example method call:
public static void main(String[] args){
ArrayList<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(3);
list1.add(5);
ArrayList<Integer> list2 = new ArrayList<>();
list2.add(2);
list2.add(4);
list2.add(6);
ArrayList<Integer> combined = combine(list1, list2);
System.out.println(combined);
}
Program outputs:
[1, 2, 3, 4, 5, 6]
======================================
import java.util.Random;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class Test{
public static void main(String[] args){
final Random r = new Random();
testaa(new int[]{1,3,5,7,9}, new int[]{2,4,6,8,10});
testaa(new int[]{10,20,30,40,50,60}, new int[]{70,80,90,100,110});
testaa(new int[]{1,11,21,31,41}, new int[]{2,3,4,32,33,34,42});
}
public static void tulosta(ArrayList<String> lista) {
System.out.print("[\"");
System.out.print(String.join("\", \"", lista));
System.out.println("\"]");
}
public static void testaa(int[] l1, int[] l2) {
ArrayList<Integer> lista1 = new ArrayList<>();
for (int a : l1) {
lista1.add(a);
}
ArrayList<Integer> lista2 = new ArrayList<>();
for (int a : l2) {
lista2.add(a);
}
System.out.println("Testing with lists ");
System.out.println("" + lista1);
System.out.println("" + lista2);
System.out.println("Combined: ");
System.out.println(combine(lista1, lista2));
System.out.println("");
}
// https://stackoverflow.com/a/189569/5324726
// combine used by testaa
public static ArrayList<Integer> combine(ArrayList<Integer> list1, ArrayList<Integer> list2){
ArrayList<Integer> combined = new ArrayList<>();
// for (int a : list1) {
// combined.add(a);
// }
// for (int a : list2) {
// combined.add(a);
// }
combined.addAll(list1);
combined.addAll(list2);
Collections.sort(combined);
return combined;
}
}
Testing with lists
[1, 3, 5, 7, 9]
[2, 4, 6, 8, 10]
Combined:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Testing with lists
[10, 20, 30, 40, 50, 60]
[70, 80, 90, 100, 110]
Combined:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]
Testing with lists
[1, 11, 21, 31, 41]
[2, 3, 4, 32, 33, 34, 42]
Combined:
[1, 2, 3, 4, 11, 21, 31, 32, 33, 34, 41, 42]