beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java – Remove specific elements from LinkedList example

By Chaitanya Singh | Filed Under: Java Collections

In the last post we shared a tutorial on how to remove a element from specific index in LinkedList. Here we will learn how to remove a specific element from the LinkedList.

Example

We will be using remove(Object o) method to perform this remove. More about this method is as follows:

public boolean remove(Object o): Removes the first occurrence of the specified element from this list, if it is present. If this list does not contain the element, it is unchanged. Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call).

import java.util.LinkedList;
public class RemoveExample {
 
 public static void main(String[] args) {
 
    // Create a LinkedList
    LinkedList<String> linkedlist = new LinkedList<String>();
 
    // Add elements to LinkedList
    linkedlist.add("Item1");
    linkedlist.add("Item2");
    linkedlist.add("Item3");
    linkedlist.add("Item4");
    linkedlist.add("Item5");
 
    // Displaying Elements before remove
    System.out.println("Before Remove:");
    for(String str: linkedlist){
       System.out.println(str);
    }
 
    // Removing "Item4" from the list
    linkedlist.remove("Item4");

    // LinkedList elements after remove
    System.out.println("\nAfter Remove:");
    for(String str2: linkedlist){
       System.out.println(str2);
    }
 }
}

Output:

Before Remove:
Item1
Item2
Item3
Item4
Item5

After Remove:
Item1
Item2
Item3
Item5

Enjoyed this post? Try these related posts

  1. How to empty an ArrayList in Java
  2. How to get sub list of Vector example in java
  3. Difference between HashMap and Hashtable
  4. Java – Get element from specific index of LinkedList example
  5. LinkedList in Java with Example
  6. How to clone an ArrayList to another ArrayList

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

  • Java Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap