Java Arraylist Retainall
# Java ArrayList retainAll() Method\\n\\n[ Java ArrayList](#)\\n\\nThe retainAll() method is used to retain only the elements in the ArrayList that are also present in the specified collection, i.e., it removes elements that are not present in the specified collection.\\n\\nThe syntax of the retainAll() method is:\\n\\narraylist.retainAll(Collection c);\\n**Note:** arraylist is an object of the ArrayList class.\\n\\n**Parameter Description:**\\n\\n* collection - The collection parameter\\n\\n### Return Value\\n\\nReturns true if elements were removed from the arraylist.\\n\\nThrows ClassCastException if the class of elements in the arraylist is incompatible with the class of elements in the specified collection.\\n\\nThrows NullPointerException if the arraylist contains null elements and the specified collection does not allow null elements.\\n\\n### Example\\n\\nRetain elements from the specified collection:\\n\\n## Example\\n\\nimport java.util.ArrayList;\\n\\nclass Main {\\n\\npublic static void main(String[] args){\\n\\n// Create a dynamic array\\n\\n ArrayList sites =new ArrayList();\\n\\n sites.add("Google");\\n\\n sites.add("Tutorial");\\n\\n sites.add("Taobao");\\n\\nSystem.out.println("ArrayList 1: "+ sites);\\n\\n// Create another dynamic array\\n\\n ArrayList sites2 =new ArrayList();\\n\\n// Add elements to the dynamic array\\n\\n sites2.add("Wiki");\\n\\n sites2.add("Tutorial");\\n\\n sites2.add("Weibo");\\n\\nSystem.out.println("ArrayList 2: "+ sites2);\\n\\n// Retain elements that exist in both lists\\n\\n sites.retainAll(sites2);\\n\\nSystem.out.println("Retained elements: "+ sites);\\n\\n}\\n\\n}\\n\\nOutput result:\\n\\nArrayList 1: [Google, Tutorial, Taobao]\\nArrayList 2: [Wiki, Tutorial, Weibo]\\nRetained elements: \\n\\nIn the above example, the retainAll() method removes elements from the arraylist that are not present in sites2, retaining only "Tutorial"γ\\n\\n---\\n\\n**Note:** retainAll() The method modifies the original arraylist.
YouTip