I need to sort an array of objects myArray based on their attributes. The attributes to sort by are given by the user so I store them in an int [] attToSortBy.
Then I use a for loop to go through the attributes in attToSortBy in which I use a lambda to create a comparator for each of them and then sort myArray with it.
The problem is that I need the attToSortBy to get the right attribute from my object so I need to use it in the lambda. I don't change the attToSortBy after I fill it with user's input but the compiler threw the variables in lambda must be effectively final error. So then I tried this:
final int[] attToSortByFinal=attToSortBy;
and it still throws the same error. How can I get the attToSortBy into my lambda? Below is the for loop and the lambda:
for (int i=attToSortBy.length;i>0;i--){
Comparator<myObject> comp=(myObject a, myObject b) ->
{return (int)(a.get(attToSortByFinal[i]))-(int)(b.get(attToSortByFinal[i]));};
}
CodePudding user response:
You can store the attribute in a closure outside the lambda. You don't need to create the final copy. And make sure your loop indexes correctly.
for (int i=attToSortBy.length-1;i>=0;i--){
String attr = attToSortBy[i]
Comparator<myObject> comp=(myObject a, myObject b) ->
{return (int)(a.get(attr))-(int)(b.get(attr));};
}
CodePudding user response:
It's the variable i that cause the error, declare int j = i in the loop, then use j as index can avoid the error. And I think is much more appropriate to put the comparision loop in Comparator, sample sort code like:
Collections.sort(list, (myArray1, myArray2) -> {
int compareResult = 0;
for (int i = 0; i < myArray1.attrToSortBy.length; i ) {
// if (myArray1.attrToSortBy[i] > myArray2.attrToSortBy[i]) {
// compareResult = 1;
// } else if (myArray1.attrToSortBy[i] == myArray2.attrToSortBy[i]) {
// compareResult = 0;
// } else {
// compareResult = -1;
// }
compareResult = Integer.compare(myArray1.get(myArray1.attrToSortBy[i]), myArray2.get(myArray2.attrToSortBy[i]));
//return compare result if it's not equal
if (compareResult != 0) return compareResult;
}
return compareResult;
});
