I have a POJO with 2 values, val1 and val2. I want to find the difference, sort a collection in ascending and find the value closest to zero.
public class Data {
private String name;
private int val1;
private int val2;
//getter-setter
}
I want to find the difference between val1 and val2 and then sort a collection, so the collection looks like
List<Data> listOfData;
and my current expression looks like
listOfData.stream()
.sorted((e1, e2) -> Integer.compare(e1.getVal1()-e1.getVal2(),
(e2.getVal1()-e2.getVal2())));
Example
Name1 16 67
Name2 10 60
Name3 27 30
Name4 17 13
I want the result to be Name3, as it had the smallest difference, how can I achieve this? My query does not sorted accordingly.
I managed to achieve it like this, but I want to convert it to Lambda expression
public void sortDifference(List<ResultantRow> tableRows, final boolean asc) {
Collections.sort(listOfData, new Comparator<Row>() {
@Override
public int compare(Row row1, Row row2) {
int differenceRow1 = difference(row1);
int differenceRow2 = difference(row2);
if (differenceRow1 > differenceRow2)
return asc ? 1 : -1;
else if (differenceRow1 < differenceRow2)
return asc ? -1 : 1;
return 0;
}
});
}
My difference is
return Math.abs(row.getVal1() - row.getVal2());
You want to sort your data in ascending order comparing the absolute difference of val1 and val2. For this, you can use Comparator.comparingInt(keyExtractor): this returns a comparator that compares the int value extracted by the given extractor.
Data data = listOfData.stream()
.sorted(comparingInt(d -> Math.abs(d.getVal1() - d.getVal2())))
.findFirst()
.get(); // or return null or throw an exception
Since the sort is in ascending order, this will return the data where the absolute difference is the closest to 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With