有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

lambda Java 8 Lamda Sort没有被调用

我有一份数据清单。我想使用自定义比较器进行排序。我有以下代码,但它没有得到执行。你能告诉我怎么了吗

我尝试将allACFs数据类型设置为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. # 1 楼答案

    没有调用自定义比较器,因为您没有从流中请求任何项。因此,排序操作被推迟到您想要获取排序结果的时候

    如果要强制调用,请在流上调用collect(Collectors.toList())

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