为什么 lambda 强迫我使用单元素数组而不是最终对象? [英] Why lambda forces me to use single element array instead of final object?

查看:24
本文介绍了为什么 lambda 强迫我使用单元素数组而不是最终对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

public class Item{
   private String name;
   //setter getter
}

和物品的集合.我想获取集合中最后一个项目的名称.为此,我只需遍历所有集合并最后使用.问题是我不知道为什么它强迫我使用一个元素的 String 数组.

And Collection of items. I would like to get name of last Item in Collection. To do that I simply iterate over all collection and use last. The problem is I dont know why it forces me to use one element String array.

为什么我必须使用:

String[] lastName = {""};
items.forEach(item -> lastName[0] = item.getName());
System.out.println(lastname[0]);

代替:

final String lastName;
items.forEach(item -> lastName = item.getName());
System.out.println(lastname);

推荐答案

你不能使 lastName 成为 String,因为在 lambda 中使用的局部变量(或匿名内部类)必须(有效地)final(见这里),即你不能在 .forEach 循环中每次执行 lambda 时覆盖它.使用数组(或其他包装器对象)时,您不会为该变量分配新值,而只会更改它的某些方面,因此它可以是最终的.

You can not make lastName a String, because a local variable that's used in a lambda (or anonymous inner class) must be (effectively) final (see here), i.e. you can not overwrite it in each execution of the lambda in the .forEach loop. When using an array (or some other wrapper object), you do not assign a new value to that variable, but only change some aspect of it, thus it can be final.

或者,您可以使用 reduce 跳到最后一项:

Alternatively, you could use reduce to skip to the last item:

String lastName = items.stream().reduce((a, b) -> b).get().getName();

或者,如注释中所述,跳过第一个 n-1 个元素,然后取第一个:

Or, as noted in comments, skip the first n-1 elements and take the first after that:

String last = items.stream().skip(items.size() - 1).findFirst().get().getName();

这篇关于为什么 lambda 强迫我使用单元素数组而不是最终对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆