Add elements in LinkedHashSet
We can use add() method of LinkedHashSet to add elements to LinkedHashSet collection
boolean add(Object obj)
It adds the element obj to the Set.
Example
- import java.util.*;
- public class LinkedHashSetAddExample {
- public static void main(String args[]) {
- LinkedHashSet<String> lhs = new LinkedHashSet<String>();
- lhs.add("java");
- lhs.add("c");
- lhs.add("c++");
- System.out.println(lhs);
- }
- }
import java.util.*; public class LinkedHashSetAddExample { public static void main(String args[]) { LinkedHashSet<String> lhs = new LinkedHashSet<String>(); lhs.add("java"); lhs.add("c"); lhs.add("c++"); System.out.println(lhs); } }
Using addAll() method
We can also add another LinkedHashSet to existing LinkedHashSet using addAll() method
Example
- import java.util.LinkedHashSet;
- public class LinkedHashSetAddAllExample {
- public static void main(String args[]) {
- LinkedHashSet<String> lhs = new LinkedHashSet<String>();
- LinkedHashSet<String> lhs1 = new LinkedHashSet<String>();
- lhs.add("java");
- lhs.add("c");
- lhs.add("c++");
- lhs1.add("python");
- lhs1.add("oracle");
- lhs.addAll(lhs1);
- System.out.println(lhs);
- }
- }
import java.util.LinkedHashSet; public class LinkedHashSetAddAllExample { public static void main(String args[]) { LinkedHashSet<String> lhs = new LinkedHashSet<String>(); LinkedHashSet<String> lhs1 = new LinkedHashSet<String>(); lhs.add("java"); lhs.add("c"); lhs.add("c++"); lhs1.add("python"); lhs1.add("oracle"); lhs.addAll(lhs1); System.out.println(lhs); } }
Note : Using addAll() , we can also add elements of another collection like list to LinkedHashSet