Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda expression for Sorting after logical operation

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());
like image 900
Vivek Avatar asked Jun 24 '26 03:06

Vivek


1 Answers

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.

like image 127
Tunaki Avatar answered Jun 26 '26 19:06

Tunaki