【问题标题】:How to exit from forEach if some condition matches in java 8如果某些条件在 java 8 中匹配,如何从 forEach 退出
【发布时间】:2016-01-15 05:35:01
【问题描述】:

如果某些条件匹配,有人可以告诉我如何退出 forEach 循环。我正在使用并行流。

下面是我的代码。

Map<int[], String[]> indexAndColNamePairs = depMapEntry.getKey();
Set<List<String>> dataRecords = depMapEntry.getValue();

for(Map.Entry<int[], String[]> indexAndColNamePair: indexAndColNamePairs.entrySet())
{
    int refColIndex = indexAndColNamePair.getKey()[0];
    Stream<List<String>> dataRecs = dataRecords.parallelStream();
    dataRecs.forEach((row) -> {
        if(referencingValue.equals(row.get(refColIndex)))
        {
            requiredColValueAndName.put(row.get(indexAndColNamePair.getKey()[1]),
                indexAndColNamePair.getValue()[1]);
        }
}); 

if(referencingValue.equals(row.get(refColIndex))) 然后我将值插入到映射中,然后我需要退出。

【问题讨论】:

  • 在 if 块末尾添加 break; 命令应该可以解决问题。
  • 我不想从 for 循环中中断,我想从 forEach 中中断。另外,在 if 块中不能使用 break 或 continue。
  • for each 仍然是一个 for 循环,只是它的不同实现。休息应该仍然有效
  • 我试过了,但它说 break 不能在循环或开关之外使用
  • @CalvinP。 OP 要求在流中使用 java 8 forEach,而不是 java 5 中引入的“for-each”循环。

标签: java foreach java-stream


【解决方案1】:

据我了解您的要求,您只想为列表中的一项执行一条语句 (requiredColValueAndName.put)。 Stream.forEach 的使用与此用例无关。而是先找到要执行语句的项目,然后再执行。


Optional<List<String>> expectedRow = dataRecs.filter(row -> referencingValue.equals(row.get(refColIndex))).findFirst();
    
if(expectedRow.isPresent()) {
requiredColValueAndName.put(
    expectedRow.get().get(indexAndColNamePair.getKey()[1]),
    indexAndColNamePair.getValue()[1]);
    
}

【讨论】:

  • .findFirst(…) 实际上是filter(…).findFirst()
【解决方案2】:

不能。来自documentation

几乎在所有情况下,终端操作都是急切的,在返回之前完成对数据源的遍历和管道的处理。只有终端操作 iterator() 和 spliterator() 不是;这些是作为“逃生舱”提供的,以在现有操作不足以完成任务的情况下启用任意客户端控制的管道遍历。

您想要的是filter()findFirst()iterate()

【讨论】:

  • ... 或者一个普通的 for-each 循环!仅仅因为我们有花哨的新工具,并不意味着我们不应该在旧工具做我们想做的事情时使用它们!
  • 确实如此。我完全同意你的看法;但这并不是真正的问题。 =)
  • 是的,我同意(我确实赞成你的回答,fwiw)。只是对 OP 的一个友好提醒,如果他们想要 break 行为,最简单的答案可能是他们已经知道皮草多年的那个。 :)
【解决方案3】:

@MrinalKSamanta 答案的更多功能变化:

indexAndColNamePairs.forEach((indices, colNames) -> {
    int refColIndex = indices[0];
    dataRecords.parallelStream()
               .filter(row -> referencingValue.equals(row.get(refColIndex)))
               .findFirst()
               .ifPresent(row ->
                   requiredColValueAndName.put(row.get(indices[1]), colNames[1]));
});

请注意,如果您不限于精确放置第一个匹配值(或者您期望最多一个匹配值),则将.findFirst() 替换为.findAny() 可能会获得更好的性能。

【讨论】:

    【解决方案4】:
    private String checkforlogin(List<String[]> ld, String iname, String ipass) {
    
        for (String[] u : ld) {
            Log.e("u[1]" ,u[1]);
            Log.e("u[2]" ,u[2]);
    
            if(u[1].toString().equals(iname) && u[2].toString().equals(ipass)){
                System.out.println("Bingo!!!" + u[0] + " " + u[1] + " " + u[2]);
                //go the the MainActivity
                retur_val = u[0];
            }else{
                if(retur_val.equals("-1"))
                {
                    retur_val = "-1";
                }else {
                    Log.e("already" , "got the value");
                }
    

    //返回retur_val;

            }
        }
        return retur_val;
    }
    

    //++++++++++++++++++++++++++++++++++++++++++++++++ retur_val 是一个 cals 变量,它是“-1”

    【讨论】:

      猜你喜欢
      • 2016-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-02
      • 2021-04-26
      • 1970-01-01
      • 1970-01-01
      • 2015-03-14
      相关资源
      最近更新 更多