Hi all ,
While developing my project , I implemented a scenario like this. I am having a LinkedList which contains , 100
Student class objects.
My scenario is ,
I need to get one particular Student class object from the LinkedList
where rollNo = 98. So I used the below code.
My pojo class is ,
public class Student {
private int rollNo ;
private String name;
// getters & setters
}
My main class is ,
public class MainClass {
List<Student> list = null;
public MainClass(){
list = new LinkedList<Student>();
}
public static void main(String... args){
MainClass mainClass = new MainClass();
mainClass.addStudentDetail();
Student obj = mainClass.getStudentObject(98);
// other Stuff with obj
}
private void addStudentDetail() {
for(int i=1; i<=100; i++){
Student obj = new Student();
obj.setRollNo(i);
obj.setName("Name"+i);
list.add(obj);
}
}
private Student getStudentObject(int rollNo) {
int listLength = list.size();
for(int i=0; i<listLength; i++){
if(list.get(i).getRollNo() == rollNo)
return list.get(i);
}
return null;
}
}
To get Student object where rollNo = 98 ,
This needs 98 iterations
.
So What happens if my List size is 1,00,000 and I need the Student
object where rollNo = 99,999 ?
Is there any other simple way to get one particular object with where condition
?
Note :
Sorry to say, I don't need to use HashMap
with rollNo as key. My need is to use only LinkedList
. That is my requirement.
Hope I will get a good solution here.