• Status: Solved
• Priority: Medium
• Security: Public
• Views: 314

# making a new List

I  have two  lists:
List<Student> studentList1
List<Student> studentList2

student class looks like below...

class Student{
private int ID
......
........

}

Now ...I want to build a a new  list

Logic:  replace  students from studentList1 with the students from studentList2  whoose studentId matches.

What is the quicker approach ?  I may have to do such operations  for  5/6  lists.
0
cofactor
• 4
• 2
1 Solution

Commented:
replace  students from studentList1 with the students from studentList2  whoose studentId matches.
Why are they not identical in all respects - how do they differ?
0

Author Commented:
they differ by some fields values -  they are just populated. I want to keep them.
0

Commented:
replace  students from studentList1 with the students from studentList2  whoose studentId matches.
Why are they not identical in all respects - how do they differ?

Assuming the Student class is uniquely identified by its ID (it should be) then it follows the ID can be used by Student.hashCode and Student.equals. For a List<Student> 'sl' then the following might be used:

``````	Set<Student> s = new HashSet<Student>(sl1);
``````
If there are instances in the second List you don't want to end up in the first, then an iterative approach might be better
0

Author Commented:
>>Set<Student> s = new HashSet<Student>(sl1);

what is sl1   and sl2 in your code ? is this the complete code ?

I am bit confused.
0

Commented:
what is sl1   and sl2 in your code
The first and second List<Student>
0

Commented:
If the order in the list is not important then use set as suggested by CEHJ.
Remember to implement equals and hashcode in Student for this to work.
Eclipse can do this for you: Source > Generate hashCode() and equals()
``````	@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
LogTest other = (LogTest) obj;
if (id != other.id)
return false;
return true;
}
``````

Also note that size of combined set can be greater than first list, i.e. combined set will have Students that were not present in first list but present in second list.
If this is not what you want, then
``````s.retainAll(sl1);
``````
0

Commented:
:)

If you need a hashCode method for Student, you can just use its ID (which should be unique)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.