javalambdajava-8java-stream

Calling method from loop and returning value using Java 8 Lambda \ Stream


I am trying to convert the below traditional for loop in Java 8. I tried iterating over the loop using stream's forEach and used a filter for contains check but I am unable to understand how to make a call to extractForDate() method and return the value. Please can you assist with the approach?

for (int i = 0; i < lines.length; i++) {
            if (lines[i].contains(FOR_DATE)) {
                String regex = "regex expression";
                forDate = extractForDate(lines[i], regex);
                java.sql.Date sd = new java.sql.Date(forDate.getTime())
                break;
            }
        }

Below is the method implementation.

    private static Date extractForDate(String Line, string regex) {
        Matcher m = Pattern.compile(regex).matcher(line);
        Date startDate = null,
        if (m.find()) {
            try {
                startDate = new SimpleDateFormat("Mddyyyy").parse(m.group(1));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return startDate;
    }

Solution

  • To convert your traditional loop to a stream, you just need to break it into steps and convert them to their corresponding stream operation. In your case: filtering, mapping, collecting.

    Your code can be re-written like so:

    List<Date> listDates = Arrays.stream(lines)
        .filter(line -> line.contains(FOR_DATE))
        .map(line -> extractForDate(line, regex))
        .collect(Collectors.toList());