方法引用vs lambda表达式

时间:2016-10-24 09:58:08

标签: java lambda java-8 method-reference

我想在下面的例子中用方法引用替换lambda表达式:

 public class Example {

        public static void main(String[] args) {
            List<String> words = Arrays.asList("toto.", "titi.", "other");
         //lambda expression in the filter (predicate)
            words.stream().filter(s -> s.endsWith(".")).forEach(System.out::println);
        }
   }

我想写一些这样的东西:

words.stream().filter(s::endsWith(".")).forEach(System.out::println);

是否可以将任何lambda表达式转换为方法引用。

2 个答案:

答案 0 :(得分:3)

无法“将任何lambda表达式转换为方法引用”,但您可以为特定目标类型实现工厂,如果这会满足重复需求:

public static <A,B> Predicate<A> bind2nd(BiPredicate<A,B> p, B b) {
    return a -> p.test(a, b);
}

有了这个,你可以写

words.stream().filter(bind2nd(String::endsWith, ".")).forEach(System.out::println);

但实际上,没有优势。从技术上讲,lambda表达式完全符合您的要求,它是最小的必要参数转换代码,表示为lambda表达式的主体,编译为合成方法和对该合成代码的方法引用。语法
s -> s.endsWith(".")也是表达该意图的最小语法。我怀疑你能找到一个仍然与Java编程语言的其余部分兼容的小构造。

答案 1 :(得分:3)

您可以使用Eclipse Collections中的$m = str_pad($m, '2', '0'); $s = str_pad($s, '2', '0'); ProductController.php on line 75: Taxon {#4409 ▼ #file: null #path: null #products: PersistentCollection {#4370 ▼ -snapshot: [] -owner: Taxon {#4409} -association: array:15 [ …15] -em: EntityManager {#2849 …10} -backRefFieldName: "taxons" -typeClass: ClassMetadata {#4479 …} -isDirty: false -initialized: false -coll: ArrayCollection {#4371 ▼ -elements: [] <----------------------------- this here } } #id: 13 #code: "test" #root: Taxon {#4369 ▶} #parent: Taxon {#4369 ▶ …2} #children: PersistentCollection {#4372 ▶} #left: 2 #right: 3 #level: 1 #translations: PersistentCollection {#4375 ▶} #currentLocale: "en_US" #currentTranslation: TaxonTranslation {#4377 ▶} #fallbackLocale: "en_US" #createdAt: null #updatedAt: null } 需要Predicate2,其中包含2个参数而不是selectWith()selectWith()的第二个参数在每次调用时都作为第二个参数传递给Predicate,每个项目都在迭代中传递一次。

selectWith()

默认情况下,Eclipse Collections非常渴望,如果你想懒惰地迭代,那么你可以使用Predicate2

MutableList<String> words = Lists.mutable.with("toto.", "titi.", "other");
words.selectWith(String::endsWith, ".").each(System.out::println);

如果您无法更改asLazy()

words.asLazy().selectWith(String::endsWith, ".").each(System.out::println);

Eclipse Collections'RichIterable还有其他几种* With方法可以很好地处理方法引用,包括ListList<String> words = Arrays.asList("toto.", "titi.", "other"); ListAdapter.adapt(words).selectWith(String::endsWith, ".").each(System.out::println); rejectWith()partitionWith(),{ {1}},detechWith()anySatisfyWith()

注意:我是Eclipse Collections的撰稿人。