What is LinkedHashSet.addAll in Java?

The LinkedHashSet class is similar to HashSet except that LinkedHashSet maintains the insertion order of elements whereas HashSet does not. Read more about LinkedHashSet here.

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 addAll effectively modifies the set so that its value is the union of 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 1 and 2, imported the LinkedHashSet and ArrayList classes.

  • From line number 5 to 8, created a new LinkedHashSet object with the name set and use the add method to add three elements (1,2,3) to the set object.

  • From line number 9 to 11, Create a new ArrayList object with the name list and use the add method to add two elements (1,4,5) to the list object.

  • In line number 14, Use the addAll method to add all the elements of list to the set. Element 1 in the list is already present in the set, so it has not been added. On the other hand, the elements 4 and 5 are not present in set, so they have been added. After calling the addAll method, the content of the set object changes so that the method returns true.

Free Resources