在Java中使匿名内部类成为lambda

在Java中使匿名内部类成为lambda,java,lambda,Java,Lambda,我需要修改我的代码,目标是(我引用)使匿名内部类成为lambda 我有一个解决这个问题的建议,但不知道lambdas在Java中是如何工作的我不知道如何将这个建议应用到我的具体案例中,有人能帮我吗 这就是我的建议 这是“错误”的版本: 现在,我的代码中的“错误”版本是: Collections.sort(commits, new Comparator<GitCommit>() { // @Override public int compare(GitCommit c1

我需要修改我的代码,目标是(我引用)使匿名内部类成为lambda

我有一个解决这个问题的建议,但不知道lambdas在Java中是如何工作的我不知道如何将这个建议应用到我的具体案例中,有人能帮我吗

这就是我的建议

这是“错误”的版本:

现在,我的代码中的“错误”版本是:

Collections.sort(commits, new Comparator<GitCommit>() {
    // @Override
    public int compare(GitCommit c1, GitCommit c2) {
        return c1.getDate().compareTo(c2.getDate());
        }
    });
Collections.sort(提交,新比较器(){
//@覆盖
公共int比较(gitcommitc1、gitcommitc2){
返回c1.getDate().compareTo(c2.getDate());
}
});
对应的“正确”版本是什么?

更改此选项:

Collections.sort(commits, new Comparator<GitCommit>() {
    // @Override
    public int compare(GitCommit c1, GitCommit c2) {
        return c1.getDate().compareTo(c2.getDate());
        }
    });
您不需要使用
集合。排序
您只需调用默认的
方法
,即:

并通过使用方法参考和
界面
进一步简化:

关于列表默认排序方法:

默认无效排序(比较器) 甚至

commits.sort(Comparator.comparing(GitCommit::getDate));

在第一种情况下,方法
映射
需要
函数
。我认为这是错误的,因为
映射器。
只要
映射器
不扩展
函数
,代码就无效。这是一种方法:

interface Mapper<T, R> extends Function<T, R> {
    default R map(T t) {
        return apply(t);
    }
}
  • 或方法参考:

    Collections.sort(commits, Comparator.comparing(GitCommit::getDate));
    
  • commits.sort((c1, c2) -> c1.getDate().compareTo(c2.getDate()));
    
    commits.sort(Comparator.comparing(GitCommit::getDate));
    
    Collections.sort(commits, Comparator.comparing(GitCommit::getDate));
    
    commits.sort(Comparator.comparing(GitCommit::getDate));
    
    interface Mapper<T, R> extends Function<T, R> {
        default R map(T t) {
            return apply(t);
        }
    }
    
    myCollection.stream().map(new Mapper<String,String>() {
        public String apply(String input) {
            return new StringBuilder(input).reverse().toString();
        }
    });
    
    Collections.sort(commits, (c1, c2) -> c1.getDate().compareTo(c2.getDate()));
    
    Collections.sort(commits, Comparator.comparing(GitCommit::getDate));