Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

379
Views
Llamar al método desde el bucle y devolver el valor usando Java 8 Lambda \ Stream

Estoy tratando de convertir el ciclo for tradicional a continuación en Java 8. Intenté iterar sobre el ciclo usando forEach de stream y usé un filtro para verificar contenido , pero no puedo entender cómo hacer una llamada al método extractForDate() y devolver el valor . Por favor, ¿puede ayudar con el enfoque?

 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; } }

A continuación se muestra la implementación del método.

 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; }
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Para usar Lambda/Stream api necesita tener una instancia de List, puede convertir sus líneas a ArrayList y hacer el foreach:

 //... List<String> linesList = new ArrayList<>(lines); linesList.stream() .filter(line -> line.contains(FOR_DATE)) //filter lines which contains FOR_DATE .map(line -> extractForDate(line, "regex")) //returns a list of Date eg List<Date> .forEach(date -> { java.sql.Date sd = new java.sql.Date(forDate.getTime()); } });
over 4 years ago · Santiago Trujillo Report

0

Si entendí su código correctamente, solo desea crear una fecha para la primera línea que coincida con su expresión. Para eso, puede usar filter() y findFirst(), que le dará un Opcional en el que puede usar map() para crear su fecha si se encuentra alguien. Separé cada paso en su propia función de mapa pero, por supuesto, puede fusionarlos en uno.

 java.sql.Date date = Arrays.stream(lines) .filter(line -> line.contains(FOR_DATE)) .findFirst() .map(line -> extractForDate(line, "regex expression")) .map(Date::getTime) .map(java.sql.Date::new) .orElse(null);
over 4 years ago · Santiago Trujillo Report

0

No se desvía tanto de lo que ya tienes. Solo necesita dividir cada paso (filtrado, mapeo, recopilación de resultados) en una función de transmisión. Esto es lo que estás buscando:

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

Aquí también hay una clase de prueba donde asumí su expresión regular y una matriz de líneas

 public class Test { public static final String FOR_DATE = "DATE:"; public static void main(String[] args) throws ParseException { String[] lines = new String[]{"DATE: 2152022", "test", "160220", "DATE: 1012001"}; String regex = "(\\d\\d{2}\\d{4})"; List<Date> listDates = Arrays.stream(lines) .filter(line -> line.contains(FOR_DATE)) .map(line -> extractForDate(line, regex)) .collect(Collectors.toList()); for (Date d : listDates) { System.out.println(d); } } 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; } }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!