Java Stream How to - Get day of week for the last day of each month in 2010 using Stream API








Question

We would like to know how to get day of week for the last day of each month in 2010 using Stream API.

Answer

/*from   ww  w. j  a  va  2 s .  c o m*/
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
  public static void main(String[] argv) {
    List<DayOfWeek> list = new ArrayList<>();

    list = (List<DayOfWeek>)Stream.of(Month.values()).map(month -> LocalDate.now()
        .withYear(2010)
        .with(month)
        .with(TemporalAdjusters.lastDayOfMonth()).getDayOfWeek())
    .collect(Collectors.toList());

    System.out.println(list);
  }
}

The code above generates the following result.