Reputation: 1
Depending on user preferences I want to compare object values of an array list and get the max values. My first approach was to define a function for object property and iterate through the array list.
private MyModel getMaxValueA(ArrayList<MyModel> myModelList) {
MyModel res = null;
for (MyModel myModel : myModelList) {
if (myModel != null) {
if (myModel.valueA() > res.valueA()) {
res = myModel;
}
} else {
res = myModel;
}
}
return res;
}
The problem is, i have 4 different values i want to compare, and to define 4 similar funktion does not seem to be the right was, so i tried it to combine all functions and added a switch/case
private MyModel getMaxValueA(ArrayList<MyModel> myModelList, Setting mySetting) {
MyModel res = null;
for (MyModel myModel : myModelList) {
if (myModel != null) {
switch (mySetting) {
case settingA:
if (myModel.valueA() > res.valueA()) {
res = myModel;
}
break;
case settingB:
if (myModel.valueB() > res.valueB()) {
res = myModel;
}
break;
........
} else {
res = myModel;
}
}
return res;
}
This is a bit shorter and only 1 instead of 4 functions, but it doesnt make me happy, too. Do you have any ideas to improve it?
Thanks.
Upvotes: 0
Views: 792
Reputation: 37813
Implement all your different needs like this:
class SettingsAComparator extends Comparator<MyModel> {
@Override
public int compare(MyModel m1, MyModel m2) {
return m1.valueA() - m2.valueA();
}
}
class SettingsBComparator extends Comparator<MyModel> {
// Please use better names.
// you can implement as many Comparators as necessary.
}
and change your method to
private MyModel getMaxValue(ArrayList<MyModel> myModelList, Comparator<MyModel> comparator) {
return Collections.max(myModelList, comparator);
}
This way, you can always add different comparators, if your class gets a new attribute, but you'll never have to worry about changing getMaxValue()
again. Also you can implement complex comparators, that take more than one attribute value into account.
Upvotes: 2
Reputation: 10997
Implement a Comparator
class MyComparator extends Comparator<MyModel> {
Setting s;
MyComparator(Setting s ){
this.setting=s;
}
public int compare(MyModel model, MyModel model2) {
//do the comparison utilizing setting
}
Edited looking at another answer: Then use Collections.max(listToBeSorted, new MyComparator(setting))
to get max value
Upvotes: 0