簡體   English   中英

在 Java 中創建一個匿名內部 class 一個 lambda

[英]Make an anonymous inner class a lambda in Java

我需要修改我的代碼,目標是(我引用)“使匿名內部 class 成為 lambda”。

我有一個解決這個問題的建議,但不知道 lambdas 在 Java 中如何工作我不知道如何將建議應用於我的具體案例,有人可以幫助我嗎?

這是我的建議

這是“錯誤”的版本:

myCollection.stream().map(new Mapper<String,String>() {
      public String map(String input) {
          return new StringBuilder(input).reverse().toString();
      }
});

這是“正確”的版本:

myCollection.stream().map(input -> new StringBuilder(input).reverse().toString());

現在,我的代碼中的“錯誤”版本是這樣的:

Collections.sort(commits, new Comparator<GitCommit>() {
    // @Override
    public int compare(GitCommit c1, GitCommit c2) {
        return c1.getDate().compareTo(c2.getDate());
        }
    });

對應的“正確”版本是什么?

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

甚至

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

改變這個:

Collections.sort(commits, new Comparator<GitCommit>() {
    // @Override
    public int compare(GitCommit c1, GitCommit c2) {
        return c1.getDate().compareTo(c2.getDate());
        }
    });

Collections.sort(commits, (c1, c2) -> c1.getDate().compareTo(c2.getDate()));

您不需要使用Collections.sort可以簡單地調用List默認method sort ,即:

commits.sort((c1, c2) -> c1.getDate().compareTo(c2.getDate()));

並通過使用方法參考interface Comparator進一步簡化:

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

關於 List 默認排序方法:

default void sort(Comparator<? super E> c) 根據指定 Comparator 產生的順序對該列表進行排序。

在第一種情況下,方法map需要Function 我認為這是錯誤的,因為Mapper. 只要Mapper不擴展Function ,代碼就仍然無效。 這是 go 的一種方法:

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

第二種情況是正確的,我假設您的目標是將匿名 function 打包到:

  • lambda 表達式:

     Collections.sort(commits, (c1, c2) -> c1.getDate().compareTo(c2.getDate()));
  • 或方法參考:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM