[英]How to avoid defining single element array in java lambda expression
I have written code segment which fetches a single element from list matching some condition. 我已经编写了代码段,该段从匹配某些条件的列表中获取单个元素。 Is there any way I could replace single element array with the object of the same type? 有什么办法可以用相同类型的对象替换单个元素数组?
final PromoSlotSize[] slot = new PromoSlotSize[1];
promoSlotSizeList.stream()
.filter(promoSlotSize -> promoSlotSize.getOfferSet().equals(Constants.HVT_RATE_OFFER_SET))
.findFirst()
.ifPresent(p-> slot[0] =p);
Your approach seems to be such overkill. 您的方法似乎过于矫kill过正。 Note that initializing an array with 请注意,使用初始化数组
final PromoSlotSize[] slot = new PromoSlotSize[1];
Makes the first and only element slot[0] = null
bu default. 将第一个也是唯一的元素slot[0] = null
bu设置为默认值。 Thus, you can make the Stream-API return the first found object PromoSlotSize
or null
again using Optional::orElse
: 因此,您可以使用Optional::orElse
使Stream-API返回找到的第一个对象PromoSlotSize
或再次返回null
:
slot[0] = promoSlotSizeList.stream()
.filter(i-> i.getOfferSet().equals(Constants.HVT_RATE_OFFER_SET))
.findFirst()
.orElse(null);
As @YCF_L says: Do you recognize that the Stream returns an object which might be used directly instead of creating an array of one element? 正如@YCF_L所说:您是否认识到Stream返回了一个可以直接使用而不是创建一个元素数组的对象? If you don't need an array as input to another method/class, do the following : 如果不需要将数组作为另一个方法/类的输入,请执行以下操作:
PromoSlotSize slot = promoSlotSizeList.stream()
.filter(i-> i.getOfferSet().equals(Constants.HVT_RATE_OFFER_SET))
.findFirst()
.orElse(null);
The code uses a trick, as only (effectively) final variables may be used from outside in the lambda. 该代码使用了一个技巧,因为只有(有效)最终变量可以在lambda中从外部使用。 Hence a final array where the first element can be set. 因此,可以设置第一个元素的最终数组。 In effect it uses imperative style coding, with a loop and a result. 实际上,它使用命令式样式编码以及循环和结果。
However the following is far better. 但是,以下情况要好得多。
Optional<PromoSlotSize> slot = promoSlotSizeList.stream()
.filter(i -> i.getOfferSet().equals(Constants.HVT_RATE_OFFER_SET))
.findAny();
slot.ifPresent(sl -> System.out.println("Slot present: " + sl));
As it can be parallelized, and the two attributes: boolean found + Slot result are incorporated in one Optional. 由于可以并行化,因此两个属性:布尔值找到+槽位结果合并在一个Optional中。
One way is to create a copy
from method on PromoSlotSize
class. 一种方法是从PromoSlotSize
类的方法创建一个copy
。 That method should take and argument of PromoSlotSize
object and populate it self with given PromoSlotSize data 该方法应采用PromoSlotSize
对象的参数,并使用给定的PromoSlotSize数据自行填充
final PromoSlotSize slot = new PromoSlotSize();
promoSlotSizeList.stream()
.filter(promoSlotSize -> promoSlotSize.getOfferSet().equals(Constants.HVT_RATE_OFFER_SET))
.findFirst().ifPresent(p-> slot.copy(p));
Assuming PromoSlotSize is a class you wrote, this should allow you to get rid of single element arrays. 假设PromoSlotSize是您编写的类,则应该使您摆脱单个元素数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.