开发者

How to break from forEach loop when exception occur

I have a forEach loop inside a for loop. Something like this.

for (Iterator iterator = notLoadedFiles.iterator(); iterator.hasNext();) {
            SwapReport swapReport = (SwapReport) iterator.next();
            Reader reader = Files.newBufferedReader(Paths.get(swapReport.getFilePath()));
            CSVParser csvParser = new CSVParser(reader, CSVFormat.D开发者_运维百科EFAULT);
            List<CSVRecord> initList = csvParser.getRecords();
            
            CSVRecord csvRecord = initList.stream().filter(record -> record.get(0).endsWith("@xxx.com")).findAny().orElse(null);
            if (csvRecord != null) {
                // partition the list
                List<List<CSVRecord>> output = ListUtils.partition(initList, chunkSize);

                // Set data by slice
                output.stream().forEach(slice -> {
                    String inParams = slice.stream().filter(record -> !record.get(0).endsWith("@xxx.com")).map(record -> "'" + record.get(0) + "'").collect(Collectors.joining(",")).toString();
                    try {
                          // Retrieve data for one slice
                          setAccountData(inParams);
                        }
                    } catch (SQLException e) {  
                        // How to break ?
                    }
                });
            }
        }

The forEach loop will execute the setAccount method. The try catch block inside the forEach loop is because setAccount throwing SQLException.

What I want to do is to stop(break) from the forEach loop in case there is an exception.

If there is an exception the inner loop will stop and for loop (outer loop) will proceed to the next element in the iterator.

How can I do that ?

Thank you


Sadly, function .ForEach() did not provided a good way to break the loop. Although adding a return statement inside this loop could let the .ForEach() to continue next loop, but I'm sure that's not what you are asking.

Solution

Therefore, you can try to use a feature call .takeWhile() introduced in Java 9. For example, the code will be:

boolean varNameYouPrefer = true;
output.stream().takeWhile(slice -> varNameYouPrefer).forEach(slice -> {
    String inParams = slice.stream().filter(record -> !record.get(0).endsWith("@xxx.com")).map(record -> "'" + record.get(0) + "'").collect(Collectors.joining(",")).toString();
    try {
            // Retrieve data for one slice
            setAccountData(inParams);
        }
    } catch (SQLException e) {  
        // To break, set varNameYouPrefer to false.
        varNameYouPrefer = false;
    }
});

References

  • Java Stream Document
  • Example of using takeWhile
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜