CodesJava

Easy learning with example program codes

How to check if a particular element exists in LinkedHashSet?


LinkedHashSet:

LinkedHashSet extends HashSet and implements the Set interface. It maintains insertion order for its elements.

We can use contains() method to check if a particular element exists in LinkedHashSet.

Example:

package com.codesjava;
 
import java.util.LinkedHashSet;
 
public class Test {
	public static void main(String args[]){
		//Create LinkedHashSet
		LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>();
                //Add elements to LinkedHashSet
		linkedHashSet.add("Jai");
		linkedHashSet.add("Mahesh");
		linkedHashSet.add("Vikas");
		linkedHashSet.add("Sahil");
		linkedHashSet.add("Sachin");
		linkedHashSet.add("Vijay");
		System.out.println("LinkedHashSet: " + linkedHashSet);
		System.out.println("LinkedHashSet contains 'Sahil':");
		System.out.println(linkedHashSet.contains("Sahil"));
	}
}

Output

LinkedHashSet: [Jai, Mahesh, Vikas, Sahil, Sachin, Vijay]
LinkedHashSet contains 'Sahil':
true


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap