Java – Check if a particular element exists in LinkedList example

This article shows how to check if a particular element exists in LinkedList . In this example we will write a java program to check if a particular element exists in a LinkedList using LinkedList contains()  method.

How to check if a particular element exists in LinkedList ?

We can check given element exists in LinkedList with the help of LinkedList contains() method . This method returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)). Let’s see java LinkedList contains() Method example .

import java.util.LinkedList;

public class ContailsElement {

public static void main(String[] args) {

LinkedList<String> linkedList = new LinkedList<String>();

linkedList.add("Mumbai");
linkedList.add("Delhi");
linkedList.add("Noida");
linkedList.add("Gao");
linkedList.add("Patna");
//print linkedlist
System.out.println(" Linklist is = "+linkedList);

//Returns true if this list contains the specified element

System.out.println(linkedList.contains("Delhi"));

System.out.println(linkedList.contains("panjab"));

}

}

Output:

Linklist is = [Mumbai, Delhi, Noida, Gao, Patna]

true

false

We have seen how to check If Element Exists in LinkedList in Java example.

Leave a Reply

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

17 − 10 =