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

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

问题描述

我有以下课程:

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

和项目集合。我想得到Collection中最后一项的名字。要做到这一点,我只需迭代所有集合并使用最后。问题是我不知道为什么它迫使我使用一个元素字符串数组。

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 a String ,因为在lambda(或匿名内部类)中使用的局部变量必须(有效地) final 请参阅此处),即您无法在每次执行lambda时覆盖它 .forEach 循环。使用数组(或其他一些包装器对象)时,不要为该变量赋值,只是改变它的某些方面,因此它可以是最终的。

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天全站免登陆