What is LinkedHashSet.addAll in Java?
The
LinkedHashSetclass is similar toHashSetexcept thatLinkedHashSetmaintains the insertion order of elements whereasHashSetdoes not. Read more aboutLinkedHashSethere.
The addAll method adds all the elements of the passed collection to the LinkedHashSet, if they’re not already present.
Syntax
boolean addAll(Collection <? extends E > c)
Parameters
This method takes the collection object, which has to be added in the set as an argument.
Return value
addAll returns true if the set changes as a result of the call, that is, if any one of the elements from Collection is added to the set. Otherwise, Collection returns false.
If the passed argument is also a set, then
addAlleffectively modifies the set so that its value is theunionof the two sets.
Code
import java.util.LinkedHashSet;import java.util.ArrayList;class addAllDemo {public static void main( String args[] ) {LinkedHashSet<Integer> set = new LinkedHashSet<>();set.add(1);set.add(2);set.add(3);ArrayList<Integer> list = new ArrayList<>();list.add(1);list.add(4);list.add(5);System.out.println("The set is "+ set);System.out.println("Is set changed - " + set.addAll(list));System.out.println("The set is "+ set);}}
Explanation
In the code above, the following steps were taken:
-
In line number
1and2, imported theLinkedHashSetandArrayListclasses. -
From line number
5to8, created a newLinkedHashSetobject with the namesetand use theaddmethod to add three elements (1,2,3) to thesetobject. -
From line number 9 to 11, Create a new
ArrayListobject with the namelistand use theaddmethod to add two elements (1,4,5) to thelistobject. -
In line number
14, Use theaddAllmethod to add all the elements oflistto theset. Element1in thelistis already present in theset, so it has not been added. On the other hand, the elements4and5are not present inset, so they have been added. After calling theaddAllmethod, the content of thesetobject changes so that the method returnstrue.