How to check the existence of particular element in the LinkedList?

How to check the existence of particular element in the LinkedList?

Previous Home Next

 

This example will show how to check the existence of particular element in the LinkedList

.we use contain(object o) method to check the existence of particular element in the LinkedList 
 
public boolean contains(Object o)
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains element

Create an object of LinkedList Lst through this object calls the contain() .and pass it to the another boolean type objec

 

package Example;
import java .util.LinkedList;
import java .util.Iterator;
public class LinklistExample {

/**
* @param args
*/
public static void main(String[] args) {
LinkedList Lst= new LinkedList(); // create object of LinkedList

// add elements to the LinkedList using add method
Lst.add("4");
Lst.add("6");
Lst.add("8");
Lst.add("10");
Lst.add("12");
Lst.add("14");
Lst.add("16");
Lst.add("18");

System.out.println("The elements of LinkedList prior to addition of other elemnts are:"+Lst);
Lst.addFirst("2"); // add element at the first positionof linklist
System.out.println("After adding element at the first position linkedList is:"+Lst);
Lst.addLast("20"); // add element at the last of linklist
System.out.println("after adding element Now the LinkedList contains:"+Lst);
// now we want add element at specific position of index using add(int index,element) method
Lst.add(5, "11");
System.out.println(" after inserting specific element at specific position :" +Lst);
// now we have to check the existence of the element in the LinkedList .we use contain(object o) method
//it will shows the result in boolean value true/false
boolean blnExists=Lst.contains("14");
System.out.println("The specific element is present in the LinkedList: "+blnExists);


The elements of LinkedList prior to addition of other elemnts are:[4, 6, 8, 10, 12, 14, 16, 18]
After adding element at the first position linkedList is:[2, 4, 6, 8, 10, 12, 14, 16, 18]
after adding element Now the LinkedList contains:[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
 after inserting specific element at specific position :[2, 4, 6, 8, 10, 11, 12, 14, 16, 18, 20]
The specific element is present in the LinkedList: true
Previous Home Next