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 extractForDate()
método 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;
}
Solución del problema
It doesn't stray that much from what you already have. You just need to break each step (filtering, mapping, collecting results) to a stream function. This is what you're looking for:
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;
}
}
No hay comentarios.:
Publicar un comentario