Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将增强的循环转换为Java 8流,筛选_Java_Java 8_Java Stream - Fatal编程技术网

将增强的循环转换为Java 8流,筛选

将增强的循环转换为Java 8流,筛选,java,java-8,java-stream,Java,Java 8,Java Stream,我正在努力学习Java8。有没有办法将下面的方法转换为Java8流、过滤器和forEach。如果是,怎么做 String[] couponList = coupons.split(","); for(String coupon:couponList) { singleCouponUsageCount = getSingleCouponUsageCount(coupon); if(singleCouponUsageCount >= totalUsageCount) retu

我正在努力学习Java8。有没有办法将下面的方法转换为Java8流、过滤器和forEach。如果是,怎么做

String[] couponList = coupons.split(",");

for(String coupon:couponList) {
  singleCouponUsageCount = getSingleCouponUsageCount(coupon);
  if(singleCouponUsageCount >= totalUsageCount)
    return 0;
}
return 1;

//

for(String coupon:couponList) {
  singleCouponUsageCount = getSingleCouponUsageCount(coupon);
  if(singleCouponUsageCount >= totalUsageCount)
    return singleCouponUsageCount;
}
return singleCouponUsageCount;

您可以对数组的元素进行
流式处理
,将它们映射到它们的使用计数,并使用
anyMatch
确定是否有任何使用计数符合应返回0的条件:

return Arrays.stream(coupons.split(","))
             .map(coupon -> getSingleCouponUsageCount(coupon))
             .anyMatch(count -> count >= totalUsageCount) ? 0 : 1;
编辑:

对于第二个代码段,如果要返回与条件匹配的第一个计数,可以编写:

return Arrays.stream(coupons.split(","))
             .map(coupon -> getSingleCouponUsageCount(coupon))
             .filter(count -> count >= totalUsageCount)
             .findFirst()
             .orElse(someDefaultValue);

你可以这样做

return Stream.of(coupons.split(","))
      .anyMatch(coupon -> getSingleCouponUsageCount(coupon) >= totalUsageCount) ? 0 : 1;

是的,您可以使用streams:

List<Integer> results = couponList
    .stream()
    .map(coupon -> getSingleCouponUsageCount(coupon))
    .filter(count -> count >= totalUsageCount ? 0 : 1)
    .collect(Collectors.toList());
List results=couponList
.stream()
.map(优惠券->GetSingleCoupOnSageCount(优惠券))
.filter(计数->计数>=totalUsageCount?0:1)
.collect(Collectors.toList());

您也可以使用
Pattern.splitAsStream()
进行此操作,它直接返回一个

// as a constant
private static final Pattern COMMA = Pattern.compile(",");

// somewhere else in a method
boolean found = COMMA.splitAsStream(coupons)
    // effectively the same as coupon -> getSingleCouponCount(count)
    .map(this::getSingleCouponCount)
    .anyMatch(count -> count >= totalUsageCount);

return found ? 0 : 1;

给定您共享的代码。一个重要的实用程序是为优惠券使用创建一个查找映射

Map<String, Long> couponUsageCount(String[] couponList) {
    return Arrays.stream(couponList)
            .collect(Collectors.toMap(Function.identity(), 
                      coupon ->> getSingleCouponUsageCount(coupon)));
}
Map couponSageCount(字符串[]couponList){
返回Arrays.stream(couponList)
.collect(Collectors.toMap(Function.identity()),
优惠券->>GetSingleCoupOnSageCount(优惠券));
}
此外,将其合并到其他两个实现中也很容易

// note: boolean instead of 0 and 1
boolean countUsageExceeds(String[] couponList, Long totalUsageCount) {
    return couponUsageCount(couponList).values()
            .stream()
            .anyMatch(usage -> usage >= totalUsageCount);
}


// better to use Optional since you might not find any such value
// same as above method returning false
Optional<Long> exceededValue(String[] couponList, Long totalUsageCount) {
    Map<String, Long> couponUsageCount = couponUsageCount(couponList);
    // use this with orElse if you want to return an absolute value from this method
    long lastValue = couponUsageCount.get(couponList[couponList.length - 1]);
    return couponUsageCount.values()
            .stream()
            .filter(usage -> usage >= totalUsageCount)
            .findFirst();
}
//注意:布尔值而不是0和1
布尔countUsageExceeds(字符串[]耦合列表,长totalUsageCount){
返回CoupOnSageCount(couponList).values()
.stream()
.anyMatch(用法->用法>=totalUsageCount);
}
//最好使用Optional,因为您可能找不到任何这样的值
//与上述方法相同,返回false
可选的exceededValue(字符串[]耦合列表,Long totalUsageCount){
映射couponSageCount=couponSageCount(couponList);
//如果要从该方法返回绝对值,请将其与orElse一起使用
long lastValue=couponSageCount.get(couponList[couponList.length-1]);
返回coupOnSageCount.values()
.stream()
.filter(用法->用法>=totalUsageCount)
.findFirst();
}

通常,您希望搜索操作短路,换句话说,在找到匹配项后立即返回。但是,与像
collect
这样的操作不同,streamapi的短路操作不容易定制

对于特定的操作,可以将操作拆分为两个,这两个操作仍然可以表示为单个表达式:

String[] couponList = coupons.split(",");

return Arrays.stream(couponList, 0, couponList.length-1)
    .map(coupon -> getSingleCouponUsageCount(coupon))
    .filter(singleCouponUsageCount -> singleCouponUsageCount >= totalUsageCount)
    .findFirst()
    .orElseGet(() -> getSingleCouponUsageCount(couponList[couponList.length-1]));

这将对除最后一个元素外的所有元素进行短路搜索,在找到匹配项后立即返回。只有在没有找到匹配项的情况下,才会处理最后一个元素并无条件返回其结果。

如果顺序重要,可能会先查找?@matt根据问题中的代码,只需查找其中任何元素是否满足条件。在编辑之前,对解决方案投了赞成票,但是如果
findFirst
未能找到任何内容,则不是默认值。放弃投票,因为评论是在编辑之后,但是…谢谢@Eran。你的解决方案非常有用,我真的学到了很多关于编写代码的新方法。顺便说一句,你应该修复你的代码
Arrays.asList()
返回一个
List
,您正在将其分配给一个数组。保留迭代解决方案,这没有问题。@MadhurBansal这两个代码块的关系如何?@MadhurBansal确定。在第二个代码段的循环之外返回的
singlecouponsagecount
的值是多少?这是默认值吗?为什么你坚持保留两个相互矛盾的代码示例?为什么不删除与您想要的不匹配的代码示例?在这种方法中,循环在达到结束条件时只迭代一次。如果在循环中找不到任何合适的事例,则应返回1。为此,代码需要为所有事例调用函数getSingleCoupOnSageCount(),即使它不是必需的。然后,它必须在最终列表中迭代,以找到合适的响应。它可以工作,但我认为它听起来不像是一个优化的解决方案。谢谢你的回答。这对我找到真正的解决办法帮助很大。