2016-01-15 46 views
1

匹配有人可以让我知道如果某些条件matches.I现在用的并行流如何从forEach循环退出如何从的forEach退出。如果某些条件的Java 8

以下是我的代码。

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)))然后我插入值映射,然后我需要退出。

+0

在if块的末尾添加'break;'命令应该可以做到。 –

+0

我不想从循环中断,我想从forEach中断。也不可能在if块中使用break或continue。 – user3743797

+0

对于每个仍然是for循环,只是它的一个不同的实现。中断应该仍然工作 –

回答

2

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

Optional<List<String>> expectedRow = dataRecs 
    .findFirst(row -> referencingValue.equals(row.get(refColIndex)))); 

if(expectedRow.isPresent()) { 
    requiredColValueAndName.put(expectedRow.get().get(indexAndColNamePair.getKey()[1]), 
           indexAndColNamePair.getValue()[1]); 
} 
+0

'.findFirst(...)'实际上是'过滤器(...).findFirst()'。 – Holger

3

不能。来自documentation

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

你想要的是要么filter()findFirst()iterate()

+2

...或每个循环的普通旧式!仅仅因为我们有新奇的工具,并不意味着我们不应该在他们做我们想要的时候使用旧工具! – yshavit

+0

确实。我完全同意你的意见。但那不是真正的问题。 =) – ktbiz

+0

是的,我同意(我也赞成你的回答,fwiw)。只是一个友好的提醒OP,如果他们想要“休息”的行为,最简单的答案可能是他们已知的毛皮年。 :) – yshavit

2

@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])); 
}); 

需要注意的是,如果你不局限于把完全相同的第一个匹配值(或您预计最多有一个匹配的值),你可能有更好的表现如果您用.findAny()替换.findFirst()