Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Lambda Sort is not getting called

Tags:

java

lambda

I have a list of data. I would like to sort using a custom comparator. I have following code but it is not getting executed. Could you please let me know what is wrong.

I tried with allACFs data type as java.util.Collection.

List<Interface> allACFs =  (List<Interface>) SearchUtil.seacrh(individualiterator, SearchUtil.startswith("type.code", "ACF"));

allACFs.stream().sorted(new Comparator<Interface>() {

    @Override
    public int compare(Interface o1, Interface o2) {
        System.out.println(o1.getType().getCode()+" : "+o2.getType().getCode()+" > "+o1.getType().getCode().compareTo(o2.getType().getCode()));
        return o1.getType().getCode().compareTo(o2.getType().getCode());
    }
});
like image 808
Debopam Avatar asked Feb 07 '26 12:02

Debopam


1 Answers

Your custom comparator is not being called because you did not request any items from the stream. Therefore, sorting operation is deferred until you want to harvest the results of sorting.

If you want to force the call, invoke collect(Collectors.toList()) on the stream:

List<Interface> list = allACFs.stream().sorted(new Comparator<Interface>() {
    @Override
    public int compare(Interface o1, Interface o2) {
        System.out.println(o1.getType().getCode()+" : "+o2.getType().getCode()+" > "+o1.getType().getCode().compareTo(o2.getType().getCode()));
        return o1.getType().getCode().compareTo(o2.getType().getCode());
    }
}).collect(Collectors.toList());
like image 156
Sergey Kalinichenko Avatar answered Feb 09 '26 07:02

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!