For example I have a list that contains 3 objects:
List<Student> studentList= new ArrayList<Student>();
list.add(new Student("name1", 5);
list.add(new Student("name3", 6);
list.add(new Student("name1", 7);
class Student{ String name; Integer grade;}
My filtering logic: if name is equal then i need to filter out the objects that have maximum grade - so keep the minimum one.
Also I do not know there the duplicates by name are in the collection.
I am stuck with this implementation:
Set<Student> setStudents= new TreeSet<Student>(new Comparator<Student>() {
@Override
public int compare(Student st1, Student st2) {
int compareName= st1.getName().compareTo(st2.getName());
if (compareName== 0){
int compareGrade = st1.getGrade().compareTo(st2.getGrade());
// ?
}
return compareName;
}
});
setStudents.addAll(studentList);
Expected output:
List with
Student("name1", 5)
Student("name3", 6);
Thank you
This solution is faster than TreeSet because use HashSet rather than TreeSet and it solve your problem completely.
here will be your student class :
and this is your test :
public class Launcher {
the output is 1 because in String "name1", the minimum value is 1;
if you want to create list first and then get that set, this is also possible:
this will give you the same result !