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

  1. import java.util.*;
  2. public class LinkedHashSetAddExample {
  3. public static void main(String args[]) {
  4.  
  5. LinkedHashSet<String> lhs = new LinkedHashSet<String>();
  6.  
  7. lhs.add("java");
  8. lhs.add("c");
  9. lhs.add("c++");
  10. System.out.println(lhs);
  11. }
  12. }
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

  1. import java.util.LinkedHashSet;
  2. public class LinkedHashSetAddAllExample {
  3. public static void main(String args[]) {
  4.  
  5. LinkedHashSet<String> lhs = new LinkedHashSet<String>();
  6. LinkedHashSet<String> lhs1 = new LinkedHashSet<String>();
  7. lhs.add("java");
  8. lhs.add("c");
  9. lhs.add("c++");
  10.  
  11. lhs1.add("python");
  12. lhs1.add("oracle");
  13. lhs.addAll(lhs1);
  14. System.out.println(lhs);
  15. }
  16. }
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

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on