Monday, January 12, 2026

Collections Sort using Lambda Expressions

-----------------------------------------


import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

import java.util.Comparator;


class CollectionsSort {

public static void main(String[] args) {

ArrayList<Integer> al = new ArrayList<Integer>();

al.add(10);

al.add(29);

al.add(17);

al.add(14);

al.add(23);

System.out.println("Before sorting " + al);

Collections.sort(al, ((I1,I2)->(I1 > I2) ? -1 : (I1 < I2) ? 1 : 0));

System.out.println("After sorting " + al);

}

}


Solution :


I1, I2 is the feed to compare(Object o1, Object o2) or compare(Integer o1, Integer o2) method


Which then checks for the


if(I1 > I2) {

return -1;

} else if(I1 < I2) {

return 1;

} else {

return 0;

}



Before sorting [10, 29, 17, 14, 23]

After sorting [29, 23, 17, 14, 10]

No comments:

Post a Comment