Remove LinkedHashSet elements

We can use remove() method of LinkedHashSet to remove elements from LinkedHashSet collection

boolean remove(Object obj)

Example

  1. import java.util.*;
  2. public class LinkedHashSetRemoveExample {
  3. public static void main(String args[]) {
  4.  
  5. LinkedHashSet lhs = new LinkedHashSet();
  6.  
  7. lhs.add(“java”);
  8. lhs.add(“c”);
  9. lhs.add(“c++);
  10. System.out.println(“LinkedHashSet before removing elements”);
  11. System.out.println(lhs);
  12. lhs.remove(“java”);
  13. System.out.println(“LinkedHashSet after removing elements”);
  14. System.out.println(lhs);
  15. }
  16. }
import java.util.*;
public class LinkedHashSetRemoveExample {
public static void main(String args[]) {

LinkedHashSet lhs = new LinkedHashSet();

lhs.add(“java”);
lhs.add(“c”);
lhs.add(“c++”);
System.out.println(“LinkedHashSet before removing elements”);
System.out.println(lhs);
lhs.remove(“java”);
System.out.println(“LinkedHashSet after removing elements”);
System.out.println(lhs);
}
}


Removing all elements at once

We can use clear() method of LinkedHashSet to remove all elements in one go

  1. import java.util.*;
  2. public class LinkedHashSetRemoveAllExample {
  3. public static void main(String args[]) {
  4.  
  5. LinkedHashSet lhs = new LinkedHashSet();
  6.  
  7. lhs.add(“java”);
  8. lhs.add(“c”);
  9. lhs.add(“c++);
  10. System.out.println(“LinkedHashSet before removing all elements”);
  11. System.out.println(lhs);
  12. lhs.clear();
  13. System.out.println(“LinkedHashSet after removing all elements”);
  14. System.out.println(lhs);
  15. }
  16. }
import java.util.*;
public class LinkedHashSetRemoveAllExample {
public static void main(String args[]) {

LinkedHashSet lhs = new LinkedHashSet();

lhs.add(“java”);
lhs.add(“c”);
lhs.add(“c++”);
System.out.println(“LinkedHashSet before removing all elements”);
System.out.println(lhs);
lhs.clear();
System.out.println(“LinkedHashSet after removing all elements”);
System.out.println(lhs);
}
}

About the Author

Karibasappa G C (KB)
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