Write a Java program to find out whether that element exist in a LinkedList or not


The LinkedList_Not class contains a main method where a linked list of strings, col_list, is created and populated with some values using the add method. The col_list contains the strings "Blue", "Green", "Pink", "Black", "Red", and "orange".

The contains method is used to check if the linked list contains a particular string. In this case, the string "Pink" is checked using col_list.contains(col) , where col is assigned the value "Pink". If the linked list contains the string "Pink", the index of "Pink" in the linked list is printed using the indexOf method, which returns the first occurrence of the specified element in the list. In this case, the index of "Pink" in the linked list is printed.

Then, the code checks for the string "Yellow" in the linked list using col_list.contains("Yellow"). Since "Yellow" is not present in the linked list, the contains method returns false, and the indexOf method is not executed, so no index is printed for "Yellow".

Source Code

import java.util.*;
public class LinkedList_Not
{
    public static void main(String[] args)
    {
        LinkedList<String> col_list = new LinkedList<String>(); 
		col_list.add("Blue");
		col_list.add("Green");
		col_list.add("Pink");
		col_list.add("Black");
		col_list.add("Red");
		col_list.add("orange"); 
        System.out.println(col_list); 
 
        String col = "Pink";
        boolean contains = col_list.contains(col); 
        if(contains)
        { 
            System.out.println(col_list.indexOf(col));	//printing it's index
        }
 
        col = "Yellow"; 
        contains = col_list.contains("Yellow"); 
        if(contains)
        { 
            System.out.println(col_list.indexOf(col));	//printing it's index
        }
    }
}

Output

[Blue, Green, Pink, Black, Red, orange]
2

Example Programs