Answer the question
In order to leave comments, you need to log in
How can the given sort code be optimized in Java?
Hello. Help if not difficult.
I completed the task and now I'm trying to figure out how to optimize it so that it looks normal. Because what comes to mind looks not normal at all.
There are two sorts of the same array of objects of the same class.
It is necessary that they be sorted from smallest to largest, taking into account certain properties, but taking into account that cells containing null should be at the very end of the array, and in front of them are all cells with a certain field equal to 0 or null (depending on which gender sorting is done) .
Here is the code:
Arrays.sort(devices, new Comparator<Device>() {
@Override
public int compare(Device o1, Device o2) {
if (o1 == null && o2 == null) {
return 0;
}
if (o1 == null) {
return 1;
}
if (o2 == null) {
return -1;
}
if (o1.getIn() == 0) {
return 1;
}
if (o2.getIn() == 0) {
return -1;
}
return Integer.compare(o1.getIn(), o2.getIn());
}
});
Arrays.sort(devices, new Comparator<Device>() {
@Override
public int compare(Device o1, Device o2) {
if (o1 == null && o2 == null) {
return 0;
}
if (o1 == null) {
return 1;
}
if (o2 == null) {
return -1;
}
if (o1.getProductionDate() == null) {
return 1;
}
if (o2.getProductionDate() == null) {
return -1;
}
return o1.getProductionDate().compareTo(o2.getProductionDate());
}
});
Answer the question
In order to leave comments, you need to log in
You have two parts in Comparators
1. comparison with zero
2. comparison of certain fields.
comparison with zero is duplicated. it's already bad. must be taken out of these two classes.
comparison of two fields is the same. those. took a certain field and compared it to a compare. also seem to be duplicated.
You can make your own comparator, but with a parameter -
it will be something like this
sort(new MyDeviceComparatorOn(Device::getIn))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question