How to populate an ArrayList until you reach the specified maximum number of elements with Java 8 threads?

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?

+4
source share
1

Stream.limit(maxSize), Stream:

public List<Messages> filterMessagesByData(Calendar filterDate, ArrayList<Messages> messagesList) {
    return messagesList.stream().filter(message -> {
        Calendar msgDate = Calendar.getInstance();
        try {
            msgDate.setTime(new SimpleDateFormat("dd/MM/yy").parse(message.getDate()));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return msgDate.compareTo(filterDate) >= 0;
    }).limit(MAX_MESSAGES_NUM).collect(Collectors.toList());
}

:

+8

Source: https://habr.com/ru/post/1608989/


All Articles