我正在学习lambda表达式.给定一个名称列表,我想计算一下开头的名字数量N.
我这样做了:
final static List<String> friends = Arrays.asList("Brian", "Nate", "Neal", "Raju", "Sara", "Scott");
public static int countFriendsStartWithN() {
return Math.toIntExact(friends
.stream()
.filter(name -> name.startsWith("N"))
.count());
}
Run Code Online (Sandbox Code Playgroud)
对count方法的调用返回一个原语,long但我想要一个int.
我曾经Math.toIntExact把long价值看作是int.
是否可以int直接在lambda表达式中获取值?
不,您的调用不适合您toIntExact的方法调用链,您的流管道.这是因为count是一个终端操作并返回一个long没有方法调用的原语.终端操作是结束流管道并产生结果(或副作用)的操作.
所以我相信你能做的最好的事情就是忍受已有的代码.恕我直言,没关系.
好吧,这是一种有点愚蠢的计算方法,无需强制转换为int:
public static int countFriendsStartWithN() {
return friends.stream()
.filter(name -> name.startsWith("N"))
.mapToInt (s -> 1)
.sum();
}
Run Code Online (Sandbox Code Playgroud)