gpt4 book ai didi

java 8 方法引用到 lambda

转载 作者:行者123 更新时间:2023-11-29 10:09:19 25 4
gpt4 key购买 nike

<分区>

我有这段代码,我尝试将方法引用(“String::length”)转换为等效的 lambda 表达式。

 Stream<String> s = Stream.of("hello", "your name", "welcome", "z");

List<String> list = s.sorted((a, b) -> Comparator.comparingInt(String::length).compare(a, b)).collect(toList());

// List<String> list = s.sorted((a, b) -> Comparator.comparingInt( p -> {return ((String)p).length();}).compare(a, b)).collect(toList());

注释行中概述了它唯一的工作方式。我需要转换参数“p”。

如果我使用 lambda 表达式并且我需要显式转换,它似乎在编译时将参数“p”的类型指定为对象。见下文:

<Object> Comparator<Object> java.util.Comparator.comparingInt(ToIntFunction<? super Object> keyExtractor)

当我使用 String::length 方法引用时,隐式参数在编译时被正确理解为 String 实例。这种情况有什么特别之处?见下文。

<String> Comparator<String> java.util.Comparator.comparingInt(ToIntFunction<? super String> keyExtractor)

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com