Any ideas? How Can I Use Comparators and Collections In Order To Sort A Text File In Different Ways? (Java)?
you've almost got it right:
For comparing integers use the following:
Integer.compareTo(int1, int2);
For comparing strings use:
string1.compareTo(string2);
For boolean types use:
Boolean.compare(boolean1, boolean2);
So you Comparator class will be the following:
new Comparator< EmployeeFX >(){
@Override
public int compare(EmployeeFX o1, EmployeeFX o2) {
return Integer.compare(o1.getId(), o2.getId());
}
};
Comparator is basically used to create multiple sort sequence. you can sort your object using any attribute.
Just one example for your reference.
public int compare(EmployeeFX emp1, EmployeeFX emp2) {
return (emp1.getId() < emp2.getId()) ? -1
: (emp1.getId() > emp2.getId()) ? 1 : 0;
}
What is your expected out put.
In this case u get the data sorted with salary wise(That is your last sort). All other previous sort become irrelevant.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.