I am new to Java 8 and I am learning threads. I am trying to populate an ArrayList of messages that have a date after the specified date. I need this new ArrayList to have a maximum of 16 elements. I tried the following:
private static final int MAX_MESSAGES_NUM = 16;
public ArrayList<Messages> filterMessagesByData(Calendar filterDate, ArrayList<Messages> messagesList) {
ArrayList<Messages> filteredMessages = new ArrayList<Messages>();
int msgCount = 0;
messagesList.stream().filter(message -> {
Calendar msgDate = new GregorianCalendar();
try {
msgDate.setTime(new SimpleDateFormat("dd/MM/yy").parse(message.getDate()));
msgCount ++;
} catch (ParseException e) {
e.printStackTrace();
throw new RuntimeException();
}
return (msgDate.compareTo(filterDate) >= 0) && msgCount < MAX_MESSAGES_NUM;
}).forEach(filteredMessages::add);
return filteredMessages;
}
but this gives me an error in the line msgCount++:
The local msgCount variable defined in the enclosing area must be final or final.
I suspect that external variables cannot be changed in a lambda expression.
Is there a way in which it can be accomplished using streams and filters?
source
share