LinkedHashSet is used to store elements in which order they were inserted. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements in the order in which they were inserted. When cycling through LinkedHashSet using an iterator, the elements will be returned to the order in which they were inserted.
We have a class Student and a LinkedHashSet of type Student, and we want to see that the LinkedHashSet contains the object or not.
// Student class
class Student {
int rollNo;
String name;
Student(int r, String s) {
rollNo = r;
name = s;
}
}
// LinkedHashSet of type Student
LinkedHashSet<Student> set = new LinkedHashSet<>();
There are two ways to find the object in the LinkedHashSet:
- Using contains() method
- Using iterate over LinkedHashSet
Method 1: Using contains() method
We can find the object in the LinkedHashSet using the contains() method in Java. The contains() method in Java returns true if the object present in LinkedHashSet otherwise, it returns false.
Java
import java.util.*;
class Student {
int rollNo;
String name;
Student( int r, String s)
{
rollNo = r;
name = s;
}
}
public class GFG {
public static void main(String[] args)
{
Student stu1 = new Student( 1 , "Akshay" );
Student stu2 = new Student( 2 , "Bina" );
Student stu3 = new Student( 3 , "Chintu" );
Student stu4 = new Student( 4 , "Dheeraj" );
LinkedHashSet<Student> set = new LinkedHashSet<>();
set.add(stu1);
set.add(stu2);
set.add(stu3);
if (set.contains(stu4))
{
System.out.println(stu4.name+ " is present in set." );
}
else
{
System.out.println(stu4.name+ " is not present in set." );
}
}
}
|
Output
Dheeraj is not present in set.
Method 2: Using iterate over LinkedHashSet:
We can also find the object in LinkedHashSet using iterate over it.
Java
import java.util.*;
class Student {
int rollNo;
String name;
Student( int r, String s)
{
rollNo = r;
name = s;
}
}
public class GFG {
public static void main(String[] args)
{
Student stu1 = new Student( 1 , "Akshay" );
Student stu2 = new Student( 2 , "Bina" );
Student stu3 = new Student( 3 , "Chintu" );
Student stu4 = new Student( 4 , "Dheeraj" );
LinkedHashSet<Student> set = new LinkedHashSet<>();
set.add(stu1);
set.add(stu2);
set.add(stu3);
for (Student stu : set)
{
if (stu == stu2)
{
System.out.println(stu.name+ " present in set." );
}
}
}
}
|
Output
Bina present in set.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
28 Jun, 2021
Like Article
Save Article