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());
}
});
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());