1

I was writing a code to validate states of my object. The code I wrote sorts the input list of objects and then does a range check.

private boolean validateStates(List<ConcessionState> concessionStateList) {
    long startRange,endRange = 0;
    Collections.sort(concessionStateList , new Comparator<ConcessionState>() {
        @Override
        public int compare(ConcessionState o1, ConcessionState o2) {
            return (int)(long)(o1.getRangeStart() - o2.getRangeStart());
        }
........
}

Is there a way to write this sort using Lambda expressions?

0

1 Answer 1

4

You use Comparator.comparing(Function<? super T,? extends U> keyExtractor).

As follows:

private boolean validateStates(List<ConcessionState> concessionStateList) {
    long startRange,endRange = 0;
    Collections.sort(concessionStateList,
                     Comparator.comparing(ConcessionState::getRangeStart));
    .......
}

If you want it in descending order, you do

    Comparator.comparing(ConcessionState::getRangeStart)
              .reversed()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.