Listlist1 = new ArrayList (); list1.add("apple"); list1.add("banana"); list1.add("orange"); List list2 = new ArrayList (); list2.add("grapes"); list2.add("kiwi"); Collections.addAll(list1, list2); // add all elements from list2 to list1 System.out.println(list1); // [apple, banana, orange, grapes, kiwi]
SetIn this example, the addAll method is used to add all elements from list1 to set1. The output after adding the elements is [50, 20, 40, 10, 30]. The java.util Collections addAll method is part of the java.util package library.set1 = new HashSet (); set1.add(10); set1.add(20); set1.add(30); List list1 = new ArrayList (); list1.add(40); list1.add(50); Collections.addAll(set1, list1); // add all elements from list1 to set1 System.out.println(set1); // [50, 20, 40, 10, 30]