2

I am pretty new to Lambdas and I'm trying to use it the following way, but it doesn't seem to work. Is it possible to have multiple declarations where ONE of those is the condition?

ArrayList<Message> msgs = new ArrayList<>(ms.values());
Calendar cal = Calendar.getInstance();

msgs.stream().filter( m -> {
    cal.setTime(m.getCreated());
    cal.get(Calendar.YEAR) == year
});

I understand that it works like:

collection.stream().filter(x -> 1 == x);

But since I need to set the Date and use it with Calendar to get the year, I would have to do this in two declarations.

I know this works:

msgs.forEach(m -> {
    cal.setTime(m.getCreated());
    if (cal.get(Calendar.YEAR) != year) {
        msgs.remove(m);
    }
});

But I want to know if it is possible to do it the way I'm trying to, or something relatively similar?

Magnilex
  • 10,219
  • 8
  • 49
  • 72
esteban rincon
  • 1,781
  • 1
  • 21
  • 40

2 Answers2

3

You need to return a value if you use curly braces. It's expecting a boolean return value. It just assumes that if there's no braces.

return cal.get(Calendar.YEAR) == year;

brian
  • 9,318
  • 4
  • 18
  • 63
1

But I want to know if it is possible to do it the way I'm trying to, or something relatively similar?

You don't even need to use the old Calendar API. Since you are using an old Date, you would need to convert it to a Java 8 ZonedDateTime, which has a simple method to get the year.

Your filter would then look like this (extracted to a method for clarity):

List<Message> filterOnYear(int year, List<Message> msgs) {
  return msgs.stream()
      .filter(msg -> msg.getCreated().toInstant().atZone(ZoneId.systemDefault()).getYear() == year)
      .collect(Collectors.toList());
}

Date#toInstant() is a new method in Java 8, which we here use as a bridge between the old Date and the Java 8 Date and Time API. The conversion might seem a bit tedious, but it is because a Date is not exactly a date, as discussed here:

Despite its name, java.util.Date represents an instant on the time-line, not a "date". The actual data stored within the object is a long count of milliseconds since 1970-01-01T00:00Z (midnight at the start of 1970 GMT/UTC).

Community
  • 1
  • 1
Magnilex
  • 10,219
  • 8
  • 49
  • 72