3

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());
    }
});
1
  • 1
    Stream.sorted() is an intermediate operation; it doesn't modify the underlying list. Just do allACFs.sort(Comparator.comparing(o -> o.getType().getCode()));. Commented Apr 4, 2018 at 2:21

1 Answer 1

2

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());
Sign up to request clarification or add additional context in comments.

1 Comment

I think the intent was to sort in-place.

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.